1 回答
TA贡献1943条经验 获得超7个赞
psutil.Process()采用一个参数 - 进程标识符 (PID)。如果调用它时没有参数或带有 ,则使用当前进程的 pid。None
在 Window 上,pid 0 是系统空闲进程,它需要特权。SYSTEM
pro=psutil.Process(0) # here's your problem
如果要获取 的内存/CPU 使用率,则必须获取 pid,然后使用 。在下面的示例中,我使用了:java.exepsutilfirefox.exe
import psutil
from ctypes import *
from ctypes.wintypes import *
class PROCESSENTRY32W(Structure):
_fields_ = [("dwSize", DWORD),
("cntUsage", DWORD),
("th32ProcessID", DWORD),
("th32DefaultHeapID", POINTER(ULONG)),
("th32ModuleID", DWORD),
("cntThreads", DWORD),
("th32ParentProcessID", DWORD),
("pcPriClassBase", LONG),
("dwFlags", DWORD),
("szExeFile", c_wchar * MAX_PATH)]
def get_processes():
TH32CS_SNAPPROCESS = 0x00000002
INVALID_HANDLE_VALUE = -1
CreateToolhelp32Snapshot = windll.kernel32.CreateToolhelp32Snapshot
CreateToolhelp32Snapshot.argtypes = [DWORD, DWORD]
CreateToolhelp32Snapshot.restype = HANDLE
Process32FirstW = windll.kernel32.Process32FirstW
Process32FirstW.argtypes = [HANDLE, POINTER(PROCESSENTRY32W)]
Process32FirstW.restype = BOOL
Process32NextW = windll.kernel32.Process32NextW
Process32NextW.argtypes = [HANDLE, POINTER(PROCESSENTRY32W)]
Process32NextW.restype = BOOL
CloseHandle = windll.kernel32.CloseHandle
CloseHandle.argtypes = [HANDLE]
CloseHandle.restype = BOOL
snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
if snapshot == INVALID_HANDLE_VALUE:
return []
try:
process_entry = PROCESSENTRY32W()
process_entry.dwSize = sizeof(PROCESSENTRY32W)
if not Process32FirstW(snapshot, byref(process_entry)):
return []
processes = []
while Process32NextW(snapshot, byref(process_entry)):
processes.append((process_entry.th32ProcessID, process_entry.szExeFile))
finally:
CloseHandle(snapshot)
#print("Closed handle")
return processes
for pid, name in get_processes():
if name == "firefox.exe":
pro = psutil.Process(pid)
cpu = pro.cpu_percent(1.0)
memory = pro.memory_full_info().uss/(1024*1024)
print(memory, cpu)
输出:
471.2890625 1.6
127.15234375 25.0
18.50390625 0.0
668.09375 0.0
706.6875 0.0
512.671875 0.0
648.953125 4.7
1037.0859375 4.7
1160.1015625 98.4
337.46484375 0.0
1418.72265625 1.6
0.90625 0.0
0.90625 0.0
添加回答
举报