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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…