Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

python - Accessing CPU/RAM usage (like with Task Manager, but via API!)?

Is there a specific way to access "task manager" information with the Windows API? I have done a fair bit of searching on the matter, but I can't seem to find an API call that will tell me either:

  • A given process's CPU/RAM usage
  • The process which is using the most CPU/RAM

Is there a way to access that information via Python or C++ (basically, via the Windows API)?

Here's what I'm essentially trying to do (in pseudo code):

app x = winapi.most_intensive_process
app y = winapi.most_RAM_usage

print x.name
print y.name
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of calling the windows API directly you can use the psutil library which is a cross-platform library that provides a lot of information about processes. It works on Windows, Linux, Mac OS, BSD and Sun Solaris and works with python from 2.4 to 3.4 in both 32 and 64 bit fashion.

In particular it's Process class has the following interesting methods:

  • cpu_times: user and system timings spent by the process from its start.
  • cpu_percent: percentage of cpu utilization since last call or in the given interval
  • memory_info: info about Ram and virtual memory usage. NOTE: the documentation explicitly states that these are the one shown by taskmgr.exe so it looks like exactly what you want.
  • memory_info_ex: extended memory information.
  • memory_percent: percentage of used memory by the process.

To iterate over all processes (in order to find the most CPU/memory hungry for example), you can just iterate over process_iter.


Here's a simple implementation of what you wanted to achieve:

import psutil

def most_intensive_process():
    return max(psutil.process_iter(), key=lambda x: x.cpu_percent(0))

def most_RAM_usage():
    return max(psutil.process_iter(), key=lambda x: x.memory_info()[0])

x = most_intensive_process()
y = most_RAM_usage()

print(x.name)
print(y.name)

Sample run on my system:

In [23]: def most_intensive_process():
    ...:     # psutil < 2.x has get_something style methods...
    ...:     return max(psutil.process_iter(), key=lambda x: x.get_cpu_percent(0))
    ...: 
    ...: def most_RAM_usage():
    ...:     return max(psutil.process_iter(), key=lambda x: x.get_memory_info()[0])

In [24]: x = most_intensive_process()
    ...: y = most_RAM_usage()
    ...: 

In [25]: print(x.name, y.name)
firefox firefox

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...