1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python使用psutil获取系统(Windows Linux)所有运行进程信息实战:CPU时间 内存使

python使用psutil获取系统(Windows Linux)所有运行进程信息实战:CPU时间 内存使

时间:2021-04-07 16:54:43

相关推荐

python使用psutil获取系统(Windows Linux)所有运行进程信息实战:CPU时间 内存使

python使用psutil获取系统(Windows Linux)所有运行进程信息实战:CPU时间、内存使用量、内存占用率、PID、名称、创建时间等;

psutil模块可以跨平台使用,支持Linux/UNIX/OSX/Windows等,它主要用来做系统监控,性能分析,进程管理等。

# 使用pip安装psutil包

pip install psutil

# process_iter方法返回的是一个迭代器,其内容就是当前正在进行的所有进程的信息,例如、CPU时间、内存使用率、名称、PID等;

psutil.process_iter(attrs=None, ad_value=None)

<generator object process_iter at 0x0000015DDB19DC78>

# 迭代获取所有的进程,从进程信息中获取进程的名称以及进程的ID;

# 以为系统以及应用软件的差异,我们在不同系统、不同时间、不同设备上面看的信息是不同的;

# 大家对应的计算机的进程也是各异的;

import psutil# Iterate over all running processfor proc in psutil.process_iter():try:# Get process name & pid from process object.processName = proc.name()processID = proc.pidprint(processName , ' ::: ', processID)except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):pass

System Idle Process ::: 0System ::: 4services.exe ::: 92Registry ::: 120lsass.exe ::: 300conhost.exe ::: 304smss.exe ::: 468RuntimeBroker.exe ::: 748rishiqing.exe ::: 760svchost.exe ::: 768csrss.exe ::: 808svchost.exe ::: 896..................................

#process_iter()函数可以用来产生生成器中的进程对象,而进程对象Process提供一个as_dict()函数用来以字典的形式获取用户期望的进程信息;

# 迭代获得的所有进程并抽取进程信息中的:名称、CPU占用率、PID(进程标识符)

# 可以获得的完整信息包括:

'pid', 'memory_percent', 'name', 'cpu_times', 'create_time', 'memory_info' etc.

PID(进程标识符)、内存占用率、名称、CPU时间、创建时间、内存信息 等;

其他更具体的可以获得信息可以参考psutil的API文档;

psutil提供的进程函数可以以字典的形式返回任何用户指定的内容;

import psutillistOfProcessNames = list()# Iterate over all running processesfor proc in psutil.process_iter():# Get process detail as dictionarypInfoDict = proc.as_dict(attrs=['pid', 'name', 'cpu_percent'])# Append dict of process detail in listlistOfProcessNames.append(pInfoDict)listOfProcessNames

[{'name': 'System Idle Process', 'cpu_percent': 768.5, 'pid': 0},{'name': 'System', 'cpu_percent': 1.5, 'pid': 4},{'name': 'services.exe', 'cpu_percent': 0.5, 'pid': 92},{'name': 'Registry', 'cpu_percent': 0.0, 'pid': 120},{'name': 'lsass.exe', 'cpu_percent': 0.0, 'pid': 300},{'name': 'conhost.exe', 'cpu_percent': 0.0, 'pid': 304},{'name': 'smss.exe', 'cpu_percent': 0.0, 'pid': 468},{'name': 'RuntimeBroker.exe', 'cpu_percent': 0.0, 'pid': 748},{'name': 'rishiqing.exe', 'cpu_percent': 0.0, 'pid': 760},{'name': 'svchost.exe', 'cpu_percent': 0.0, 'pid': 768},{'name': 'csrss.exe', 'cpu_percent': 0.0, 'pid': 808},{'name': 'svchost.exe', 'cpu_percent': 0.0, 'pid': 896},{'name': 'wininit.exe', 'cpu_percent': 0.0, 'pid': 904},..................................]

# 获取当前系统的进程并按照内存使用量排序;

# 它将遍历所有运行进程的列表,并将id和name作为dict获取内存使用情况。

# Process类提供了进程的内存信息,它从进程中获取虚拟内存使用情况,然后将每个进程的字典添加到一个列表中。最后根据关键虚拟机对字典列表进行排序,所以进程列表会根据内存使用情况进行排序。

import psutildef getListOfProcessSortedByMemory():'''Get list of running process sorted by Memory Usage'''listOfProcObjects = []# Iterate over the listfor proc in psutil.process_iter():try:# Fetch process details as dictpinfo = proc.as_dict(attrs=['pid', 'name', 'username'])pinfo['vms'] = proc.memory_info().vms / (1024 * 1024)# Append dict to listlistOfProcObjects.append(pinfo);except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):pass# Sort list of dict by key vms i.e. memory usagelistOfProcObjects = sorted(listOfProcObjects, key=lambda procObj: procObj['vms'], reverse=True)return listOfProcObjectsgetListOfProcessSortedByMemory()

[{'name': 'python.exe','username': 'user','pid': 16276,'vms': 966.26953125},{'name': 'dwm.exe', 'username': None, 'pid': 26132, 'vms': 709.0234375},{'name': 'pythonw.exe','username': 'user','pid': 23660,'vms': 564.61328125},{'name': 'mcshield.exe', 'username': None, 'pid': 6932, 'vms': 469.2578125},{'name': 'test.exe','username': 'user','pid': 16292,'vms': 456.34765625},..................................]

# 完整代码参考如下:

import psutildef getListOfProcessSortedByMemory():'''Get list of running process sorted by Memory Usage'''listOfProcObjects = []# Iterate over the listfor proc in psutil.process_iter():try:# Fetch process details as dictpinfo = proc.as_dict(attrs=['pid', 'name', 'username'])pinfo['vms'] = proc.memory_info().vms / (1024 * 1024)# Append dict to listlistOfProcObjects.append(pinfo);except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):pass# Sort list of dict by key vms i.e. memory usagelistOfProcObjects = sorted(listOfProcObjects, key=lambda procObj: procObj['vms'], reverse=True)return listOfProcObjectsdef main():print("*** Iterate over all running process and print process ID & Name ***")# Iterate over all running processfor proc in psutil.process_iter():try:# Get process name & pid from process object.processName = proc.name()processID = proc.pidprint(processName , ' ::: ', processID)except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):passprint('*** Create a list of all running processes ***')listOfProcessNames = list()# Iterate over all running processesfor proc in psutil.process_iter():# Get process detail as dictionarypInfoDict = proc.as_dict(attrs=['pid', 'name', 'cpu_percent'])# Append dict of process detail in listlistOfProcessNames.append(pInfoDict)# Iterate over the list of dictionary and print each elemfor elem in listOfProcessNames:print(elem)print('*** Top 5 process with highest memory usage ***')listOfRunningProcess = getListOfProcessSortedByMemory()for elem in listOfRunningProcess[:5] :print(elem)if __name__ == '__main__':main()

参考:/giampaolo/psutil

参考:Python : Get List of all running processes and sort by highest memory usage

参考:python 实时得到cpu和内存的使用情况方法

参考:.NET(C#):获取进程的CPU使用状况

参考:Python - get process names,CPU,Mem Usage and Peak Mem Usage in windows

参考:psutil 4.0.0 and how to get “real” process memory and environ in Python

参考:Python编程——psutil模块的使用详解

python使用psutil获取系统(Windows Linux)所有运行进程信息实战:CPU时间 内存使用量 内存占用率 PID 名称 创建时间等;

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。