怎么用python中psutil模块写获取健康监控进程号并比对
时间: 2023-12-25 16:03:34 浏览: 157
可以使用psutil模块来获取系统中运行的进程信息,并进行健康监控和比对。以下是一个示例代码:
```python
import psutil
def get_process_info(process_name):
process_info = []
for proc in psutil.process_iter(['pid', 'name']):
if proc.info['name'] == process_name:
process_info.append(proc.info)
return process_info
def compare_process_health(process_name):
process_info = get_process_info(process_name)
if len(process_info) < 2:
print("There are not enough instances of the process running.")
return
# Compare the health of the processes
for i in range(len(process_info) - 1):
cpu_percent = psutil.cpu_percent(interval=1)
mem_percent = psutil.virtual_memory().percent
pid1 = process_info[i]['pid']
pid2 = process_info[i+1]['pid']
print(f"Comparing health of process {pid1} and {pid2}:")
print(f"CPU Usage: {cpu_percent}%")
print(f"Memory Usage: {mem_percent}%")
print()
# Example usage
compare_process_health("python")
```
上述代码中的`get_process_info`函数会获取指定进程名称的所有进程信息。然后,`compare_process_health`函数会比对这些进程的健康状况,例如 CPU 使用率和内存使用率。请注意,此处仅比对了连续两个实例的进程信息。
你可以将`compare_process_health`函数中的`process_name`参数替换为你想要监控的进程名称,例如 "python"。运行代码后,它将打印出比对的结果,包括 CPU 使用率和内存使用率。
请注意,psutil模块需要先安装才能使用。你可以通过运行`pip install psutil`来安装它。
阅读全文