在Windows中用Python获取计算机内存使用情况
我怎么能从Python中查看电脑的整体内存使用情况,电脑是运行Windows XP的?
3 个回答
0
你可以在WMI中查询性能计数器。我之前做过类似的事情,不过是查询磁盘空间。
一个非常有用的链接是 Tim Golden的Python WMI教程。
23
你也可以直接从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))
虽然在这个情况下,它可能没有WMI那么有用,但这绝对是一个不错的小技巧,可以留着备用。
14
你需要使用 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"