python-根据进程名获取windows系统进程pid,定时监控多个进程性能并写入csv文件
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import time
import psutil
def get_pid(name):
pids = psutil.process_iter()
for pid in pids:
if(pid.name() == name):
return(pid.pid)
def write_csv(p,pidnum,pidname):
current_time = time.strftime('%Y%m%d-%H%M%S',time.localtime(time.time()))
cpu_percenta = p.cpu_percent()
mem_percenta = p.memory_percent()
line = str(pidname) + ',' + str(pidnum) + ',' + current_time + ',' + str(cpu_percenta) + ',' + str(mem_percenta)
print (line)
f.write(line + "\n")
filenamelist = ['WeChat.exe','firefox.exe']
pidlist = []
i = 0
while i < len(filenamelist):
pidlist.append(get_pid(filenamelist[i]))
i = i + 1
# get process
interval = 3 # polling seconds
# monitor process and write data to file
with open("process_monitor_" + ".csv", "a+") as f:
f.write("pidname,pidnum,time,cpu%,mem%\n") # titles
while True:
n = 0
while n < len(pidlist):
pid = int(pidlist[n])
p = psutil.Process(pid)
write_csv(p,pidlist[n],filenamelist[n])
n = n + 1
time.sleep(interval)
ctrl+c 退出while True

浙公网安备 33010602011771号