1. 安装psutil模块
在Python中获取操作系统用户进程的详细信息需要使用psutil模块。可以使用以下命令在终端中安装psutil模块:
pip install psutil
2. 获取进程列表
可以使用以下代码获取当前操作系统中所有进程的详细信息:
import psutil
processes = []
for process in psutil.process_iter():
try:
process_info = process.as_dict(attrs=['pid', 'name', 'username', 'cpu_percent', 'memory_info'])
processes.append(process_info)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
print(processes)
以上代码将获取所有进程的pid、name、username、cpu_percent和memory_info信息,并将其存储在名为processes的列表中。
3. 获取单个进程的详细信息
可以使用以下代码获取特定PID进程的详细信息:
import psutil
pid = 22272
process = psutil.Process(pid) # 如果PID不存在,则报错:psutil.NoSuchProcess: process PID not found (pid=1234)
process_info = process.as_dict(attrs=['pid', 'name', 'username', 'cpu_percent', 'memory_info'])
print(process_info)
以上代码将获取PID为1234的进程的pid、name、username、cpu_percent和memory_info信息,并将其打印到终端。
{'username': 'DESKTOP-2N10T7M\\Administrator', 'cpu_percent': 0.0, 'name': 'chrome.exe', 'memory_info': pmem(rss=38707200, vms=15835136, num_page_faults=81419, peak_wset=63057920, wset=38707200, peak_paged_pool=710872, paged_pool=591064, peak_nonpaged_pool=301184, nonpaged_pool=20872, pagefile=15835136, peak_pagefile=55029760, private=15835136), 'pid': 22272}
包括:进程状态、名称、CPU占用率、进程ID、内存占用率、进程CMDLine、进程所属用户、进程所处路径、启动时间、进程磁盘IO
【扩展:还可获取进程网络资源使用率】
class SystemInfo(object):
"""
Get operating system information
"""
def __init__(self):
pass
def process_info(self):
"""
:return: A list of all process details of the system
"""
proc, all_processes = [], psutil.process_iter()
for items in all_processes:
try:
procinfo = items.as_dict(attrs=["pid", "name"])
try:
#the process start path
p_path_cwd = items.cwd().decode("gbk")
#the process accounts for system memory uasge
proc_mem_percent = items.memory_percent()
#the process starts cmdline content
cmdlines = str(items.cmdline())
#the process accounts for system CPU usage
cpu_percent = items.cpu_percent(interval=1)
except Exception as e:
try:
p_path_cwd = items.exe()
except Exception as e: p_path_cwd = e.name
p_status, p_create_time, proc_user, proc_io_info = items.status(), items.create_time(),items.username() , {}
try:
proc_io = items.io_counters()
proc_io_info["ReadCount"] = proc_io.read_count
proc_io_info["WriteCount"] = proc_io.write_count
proc_io_info["ReadBytes"] = proc_io.read_bytes
proc_io_info["WriteBytes"] = proc_io.write_bytes
except Exception:pass
procinfo.update({"path": p_path_cwd,
"cmdline":cmdlines,
"cpu_percent":cpu_percent,
"status": p_status,
"CreateTime": p_create_time,
"MemPercent": proc_mem_percent,
"user": proc_user,
"DiskIo": proc_io_info})
except Exception:pass
finally:
proc.append(procinfo)
return proc
if __name__ == '__main__':
SystemInfo().process_info()
Linux部分实例结果:
[{'status': 'running', 'name': 'python', 'cpu_percent': 0.0, 'pid': 4451, 'MemPercent': 0.3388184396693485, 'cmdline': "['python', 'process_info.py']", 'user': 'root', 'path': u'/opt/temp', 'CreateTime': 1498617080.89, 'DiskIo': {'ReadCount': 3598, 'WriteCount': 0, 'ReadBytes': 430080, 'WriteBytes': 0}},
{'status': 'sleeping', 'name': 'tuned', 'cpu_percent': 0.0, 'pid': 1049, 'MemPercent': 0.5671346113520732, 'cmdline': "['/usr/bin/python', '-Es', '/usr/sbin/tuned', '-l', '-P']", 'user': 'root', 'path': u'/', 'CreateTime': 1498616948.98, 'DiskIo': {'ReadCount': 1043, 'WriteCount': 71, 'ReadBytes': 2007040, 'WriteBytes': 12288}},
{'status': 'sleeping', 'name': 'jzagent', 'cpu_percent': 0.0, 'pid': 2904, 'MemPercent': 0.02069330861172731, 'cmdline': "['/opt/jzagent/jzagent', 'terminal']", 'user': 'root', 'path': u'/', 'CreateTime': 1498616960.4, 'DiskIo': {'ReadCount': 9, 'WriteCount': 0, 'ReadBytes': 1941504, 'WriteBytes': 0}}]
windows部分实例结果:
[{'status': 'running', 'name': 'python.exe', 'cpu_percent': 0.0, 'pid': 12120, 'MemPercent': 0.15557206974991283, 'cmdline': "['C:\\\\Python27\\\\python.exe', 'E:/codes/Python_codes/process_info.py']", 'user': u'DESKTOP-MVTK6UK\\SteveRocket', 'path': u'E:\\codes\\Python_codes', 'CreateTime': 1498615524.0, 'DiskIo': {'ReadCount': 165L, 'WriteCount': 0L, 'ReadBytes': 618846L, 'WriteBytes': 0L}},
{'status': 'running', 'name': 'python.exe', 'cpu_percent': 1.6, 'pid': 16112, 'MemPercent': 0.3357386080591733, 'cmdline': "['C:\\\\Python27\\\\python.exe', 'run.py', 'python_application']", 'user': u'DESKTOP-MVTK6UK\\SteveRocket', 'path': u'E:\\application_api', 'CreateTime': 1498614632.0, 'DiskIo': {'ReadCount': 1061L, 'WriteCount': 20L, 'ReadBytes': 4474306L, 'WriteBytes': 1299L}}]
更多资料 · 微信公众号搜索【CTO Plus】关注后,获取更多,我们一起学习交流。
关于公众号的描述访问如下链接