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

Posted Data+Science+Insight

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python使用psutil获取系统(Windows Linux)所有运行进程信息实战:CPU时间内存使用量内存占用率PID名称创建时间等;相关的知识,希望对你有一定的参考价值。

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 process
for proc in psutil.process_iter():
    try:
        # Get process name & pid from process object.
        processName = proc.name()
        processID = proc.pid
        print(processName , ' ::: ', processID)
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
        pass
System Idle Process  :::  0
System  :::  4
services.exe  :::  92
Registry  :::  120
lsass.exe  :::  300
conhost.exe  :::  304
smss.exe  :::  468
RuntimeBroker.exe  :::  748
rishiqing.exe  :::  760
svchost.exe  :::  768
csrss.exe  :::  808
svchost.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 psutil
listOfProcessNames = list()
# Iterate over all running processes
for proc in psutil.process_iter():
   # Get process detail as dictionary
   pInfoDict = proc.as_dict(attrs=['pid', 'name', 'cpu_percent'])
   # Append dict of process detail in list
   listOfProcessNames.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 psutil
def getListOfProcessSortedByMemory():
    '''
    Get list of running process sorted by Memory Usage
    '''
    listOfProcObjects = []
    # Iterate over the list
    for proc in psutil.process_iter():
       try:
           # Fetch process details as dict
           pinfo = proc.as_dict(attrs=['pid', 'name', 'username'])
           pinfo['vms'] = proc.memory_info().vms / (1024 * 1024)
           # Append dict to list
           listOfProcObjects.append(pinfo);
       except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
           pass
    # Sort list of dict by key vms i.e. memory usage
    listOfProcObjects = sorted(listOfProcObjects, key=lambda procObj: procObj['vms'], reverse=True)
    return listOfProcObjects


getListOfProcessSortedByMemory()
[{'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 psutil
def getListOfProcessSortedByMemory():
    '''
    Get list of running process sorted by Memory Usage
    '''
    listOfProcObjects = []
    # Iterate over the list
    for proc in psutil.process_iter():
       try:
           # Fetch process details as dict
           pinfo = proc.as_dict(attrs=['pid', 'name', 'username'])
           pinfo['vms'] = proc.memory_info().vms / (1024 * 1024)
           # Append dict to list
           listOfProcObjects.append(pinfo);
       except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
           pass
    # Sort list of dict by key vms i.e. memory usage
    listOfProcObjects = sorted(listOfProcObjects, key=lambda procObj: procObj['vms'], reverse=True)
    return listOfProcObjects

def main():
    print("*** Iterate over all running process and print process ID & Name ***")
    # Iterate over all running process
    for proc in psutil.process_iter():
        try:
            # Get process name & pid from process object.
            processName = proc.name()
            processID = proc.pid
            print(processName , ' ::: ', processID)
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    print('*** Create a list of all running processes ***')
    listOfProcessNames = list()
    # Iterate over all running processes
    for proc in psutil.process_iter():
       # Get process detail as dictionary
       pInfoDict = proc.as_dict(attrs=['pid', 'name', 'cpu_percent'])
       # Append dict of process detail in list
       listOfProcessNames.append(pInfoDict)
    # Iterate over the list of dictionary and print each elem
    for 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()

参考:https://github.com/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名称创建时间等;的主要内容,如果未能解决你的问题,请参考以下文章

python获取系统信息模块psutil

python-psutil模块

Psutil

python之psutil模块获取系统信息

python 获取cpu内存硬盘等实时信息 psutil

Python系统性能信息模块psutil