首页 > 解决方案 > 如何使用python保存内存、pid和进程

问题描述

如何使用python保存内存、pid和进程

import psutil    
tasklist=['firefox']
out=[]
for proc in psutil.process_iter():
    if any(task in proc.name() for task in tasklist):
        out.append([{'pid' : proc.pid, 'name' : proc.name()}])
for o in out[:]:
    print(o)
name = [j['name'] for i in out for j in i]
print (name)

检索内存使用情况和 Cpu 使用情况

pmap 413 | tail -n 1

total          2987968K

413是火狐的pid

 ps -p 413 -o %cpu,%mem

%CPU %MEM
 0.1  3.2

如何将内存使用率和 CPU 使用率添加到字典所需的输出

[{'pid': 413, 'name': 'firefox','cpu':0.1, 'mem':3.2 }]

标签: pythondictionaryprocesssubprocess

解决方案


Process实例有各自的方法来表示 cpu/内存使用百分比:

...
out.append([{'pid' : proc.pid, 'name' : proc.name(),
                     'cpu': proc.cpu_percent(), 'mem': proc.memory_percent()}])

https://psutil.readthedocs.io/en/latest/#psutil.Process.cpu_percent


推荐阅读