用python编写一个系统监控程序,需要每隔一秒钟记录系统每个进程的资源占用和整体的资源占用情况,并输出成json,保存到文本文件。
python
import psutil
import json
import time
def get_process_usage():
process_list = []
for proc in psutil.process_iter(['pid', 'name', 'username', 'cpu_percent', 'memory_percent']):
process_info = proc.info
process_list.append({
'pid': process_info['pid'],
'name': process_info['name'],
'username': process_info['username'],
'cpu_percent': process_info['cpu_percent'],
'memory_percent': process_info['memory_percent']
})
return process_list
def get_system_usage():
cpu_percent = psutil.cpu_percent()
memory_percent = psutil.virtual_memory().percent
return {
'cpu_percent': cpu_percent,
'memory_percent': memory_percent
}
def main():
while True:
system_usage = get_system_usage()
process_usage = get_process_usage()
data = {
'system': system_usage,
'processes': process_usage
}
json_data = json.dumps(data, indent=4)
# 输出JSON数据
print(json_data)
# 保存JSON数据到文件
with open('system_monitor.json', 'w') as file:
file.write(json_data)
time.sleep(1)
if __name__ == "__main__":
main()