杨__羊羊
psutil.Process()采用一个参数 - 进程标识符 (PID)。如果调用它时没有参数或带有 ,则使用当前进程的 pid。None在 Window 上,pid 0 是系统空闲进程,它需要特权。SYSTEMpro=psutil.Process(0) # here's your problem如果要获取 的内存/CPU 使用率,则必须获取 pid,然后使用 。在下面的示例中,我使用了:java.exepsutilfirefox.exeimport psutilfrom 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 processesfor 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.6127.15234375 25.018.50390625 0.0668.09375 0.0706.6875 0.0512.671875 0.0648.953125 4.71037.0859375 4.71160.1015625 98.4337.46484375 0.01418.72265625 1.60.90625 0.00.90625 0.0