要实现一个实时监控系统占用率的Python工具,我们可以使用`psutil`库来获取系统进程信息,然后计算各个进程所占用的CPU时间。以下是一个简单的示例:
首先,确保已经安装了`psutil`库,如果没有安装,可以使用以下命令安装:
```bash
pip install psutil
```
接下来,我们编写一个Python脚本来实现实时监控功能:
```python
import os
import time
import psutil
def get_process_cpu_time(pid):
"""获取指定进程的CPU时间"""
try:
return psutil.Process(pid).cpu_times()[1]
except (IndexError, KeyError):
return None
def main():
while True:
now = time.time()
process_cpu_time = {}
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_info']):
if proc.info['name'] == 'python':
if proc.info['pid'] in process_cpu_time:
process_cpu_time[proc.info['pid']] += get_process_cpu_time(proc.info['pid'])
else:
process_cpu_time[proc.info['pid']] = get_process_cpu_time(proc.info['pid'])
print("当前进程占用率:")
for pid, cpu_time in process_cpu_time.items():
print(f"{pid}: {cpu_time / 100:.2f}%")
time.sleep(60)
if __name__ == "__main__":
main()
```
这个脚本会每隔60秒输出一次当前进程占用率。你可以根据需要修改这个脚本,例如添加更多的监控指标、支持其他操作系统等。