Python - 获取Windows中进程名称、CPU使用率、内存使用率和峰值内存使用率

28

我想要获取进程名称、CPU使用率、内存使用量和峰值内存使用量的列表。我希望可以使用ctypes,但愿意听取其他选项。感谢您的时间。


1
你找不到比psutil更好的了。 - JBernardo
在Windows中,你最好的选择可能是性能计数器。 - ren
4个回答

44
你可以使用 psutil。例如,获取进程名称列表:
process_names = [proc.name() for proc in psutil.process_iter()]

获取 CPU 使用信息请使用 psutil.cpu_percent 或者 psutil.cpu_times。 获取内存使用情况请使用 psutil.virtual_memory

请注意,psutil 支持 Linux、OS X、Windows、Solaris 和 FreeBSD,并支持 Python 2.4 至 3.3 版本。


5
psutil能否获取每个进程的网络统计信息?我谷歌搜索并阅读了大约一个小时的文档,但没有找到相关信息。 - chester89
1
@chester89 这与此问题无关。请尝试在SO上搜索有关网络使用的psutil问题,如果您没有找到令人满意的答案,请继续提出新问题。无论如何,您都应该检查Process.connections(https://pythonhosted.org/psutil/#psutil.Process.connections)。 - Bakuriu
如何通过此模块知道它正在使用的带宽。 - Ravi Shanker Reddy

3

我喜欢在Windows上使用wmic。你可以从命令行运行它,因此可以从Python中运行它。

from subprocess import Popen,PIPE
proc = Popen('wmic cpu',stdout=PIPE, stderr=PIPE)
print str(proc.communicate())

wmic命令可以轻松获取进程、CPU和内存信息。只需使用wmic cpuwmic processwmic memphysical即可。通过使用wmic <alias> get <attribute>,您还可以过滤出某些属性。您可以使用wmic /?获取所有命令的列表。希望这有所帮助!您可以在此处查看WMIC的官方文档:http://technet.microsoft.com/en-us/library/bb742610.aspx

谢谢,那太好了,但需要以管理员身份运行,有没有办法在使用命令行之前以管理员身份运行它? - Daniel

1
这段 Python 3.3 代码适用于 UAC 完全关闭的 Windows 7。
import psutil
import time

def processcheck(seekitem):
    plist = psutil.get_process_list()
    str1=" ".join(str(x) for x in plist)
    if seekitem in str1:
        print ("Requested process is running")   

processcheck("System")

0

"psutil能不能针对每个进程获取网络统计信息?我谷歌了一个小时,阅读了文档,但没有找到任何相关的信息。 —— chester89"
不要担心chester89,这有我来帮你:

import psutil#God-sent module
for i in range(2):#looping twice given https://psutil.readthedocs.io/en/latest/#psutil.Process.cpu_percent '''Warning the first time this method is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore.'''
    for process0 in psutil.process_iter():#for each process running...
        print(process0.name(),process0.cpu_percent())#...print the name and how much of the overall CPU utilization does this process makes up!
    print('\n'*20)#again, due to the above comment -> "Warning", only the section after this blank space will have useful values!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接