通过 python 获取内存使用情况

Getting memory usage by python

我在使用 psutil 检索系统内存使用时遇到问题。

当我 运行 我的代码时,它会正确检索 cpu 用法,但是当它尝试获取内存时,它会抛出 AccessDenied 错误。

代码:

if(pi['name']=='java.exe'):
    pro=psutil.Process(0)
    cpu=pro.cpu_percent(1)
    memory=pro.memory_full_info().uss/(1024*1024)
    return memory,cpu

错误信息:

psutil.AccessDenied (pid=0)

如何获取内存使用情况?

psutil.Process() 接受一个参数——进程标识符 (PID)。如果调用时不带参数或使用 None,则使用当前进程的 pid。

在 Window 上,pid 0 是 系统空闲进程,它需要 SYSTEM 权限。

pro=psutil.Process(0) # here's your problem

如果您想获得 java.exe 的 memory/cpu 用法,您必须获得 pid,然后使用 psutil。在下面的示例中,我使用了 firefox.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