每30秒统计一次windows系统,指定的程序的内存使用占比,并写入到csv文件;
import psutil
import time
import os
# 搜索名称中包含"XX"的进程
target_process_name = "WeCh"
def get_processes_with_name(name_part):
processes_list = []
# 获取系统总内存
total_memory = psutil.virtual_memory().total
for proc in psutil.process_iter():
try:
# 获取进程名称(注意:进程名称可能包含路径)
processName = proc.name()
# processID = proc.pid
# 检查进程名称是否包含目标字符串(不区分大小写)
if name_part.lower() in processName.lower():
pinfo = proc.as_dict(attrs=['pid', 'name', 'cwd'])
pinfo['memory_percent_usage'] = "{:.2%}".format(proc.memory_info().rss / total_memory)
processes_list.append(pinfo)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
# 忽略那些已经不存在、没有权限访问或僵尸进程的情况
pass
return processes_list
# 获取当前文件路径,并拼接存放文件的路径
file_dir = os.path.dirname(__file__)
file_path = os.path.join(file_dir, 'processes_info.csv')
# print(file_path)
# 循环调用
while True:
processes = get_processes_with_name(target_process_name)
for process in processes:
current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
if os.path.exists(file_path):
with open(file_path, 'a', encoding='utf-8') as fp:
result = str(process["pid"]) + ',' + process['name'] + ',' + process["cwd"] + ',' + str(
process["memory_percent_usage"]) + ',' + str(current_time) + '\n'
fp.write(result)
else:
with open(file_path, 'w', encoding='utf-8') as fp:
result = str(process["pid"]) + ',' + process['name'] + ',' + process["cwd"] + ',' + str(
process["memory_percent_usage"]) + ',' + str(current_time) + '\n'
fp.write(result)
# 等待N秒后再次检查
time.sleep(30)