使用Python在Windows中获取计算机的内存使用情况

Cla*_*diu 13 python memory winapi memory-management pywin32

如何判断计算机的整体内存使用情况来自于在Windows XP上运行的Python?

Set*_*eth 21

您也可以直接从python调用GlobalMemoryStatusEx()(或任何其他kernel32或user32导出):

import ctypes

class MEMORYSTATUSEX(ctypes.Structure):
    _fields_ = [
        ("dwLength", ctypes.c_ulong),
        ("dwMemoryLoad", ctypes.c_ulong),
        ("ullTotalPhys", ctypes.c_ulonglong),
        ("ullAvailPhys", ctypes.c_ulonglong),
        ("ullTotalPageFile", ctypes.c_ulonglong),
        ("ullAvailPageFile", ctypes.c_ulonglong),
        ("ullTotalVirtual", ctypes.c_ulonglong),
        ("ullAvailVirtual", ctypes.c_ulonglong),
        ("sullAvailExtendedVirtual", ctypes.c_ulonglong),
    ]

    def __init__(self):
        # have to initialize this to the size of MEMORYSTATUSEX
        self.dwLength = ctypes.sizeof(self)
        super(MEMORYSTATUSEX, self).__init__()

stat = MEMORYSTATUSEX()
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))

print("MemoryLoad: %d%%" % (stat.dwMemoryLoad))
Run Code Online (Sandbox Code Playgroud)

在这种情况下,不一定像WMI一样有用,但绝对是一个很好的技巧,你的后袋.


Mic*_*ene 11

你会想要使用wmi模块.像这样的东西:

import wmi
comp = wmi.WMI()

for i in comp.Win32_ComputerSystem():
   print i.TotalPhysicalMemory, "bytes of physical memory"

for os in comp.Win32_OperatingSystem():
   print os.FreePhysicalMemory, "bytes of available memory"
Run Code Online (Sandbox Code Playgroud)