【发布时间】:2011-01-02 07:38:07
【问题描述】:
我如何从运行在 Windows XP 上的 Python 得知计算机的总体内存使用情况?
【问题讨论】:
标签: python memory winapi memory-management pywin32
我如何从运行在 Windows XP 上的 Python 得知计算机的总体内存使用情况?
【问题讨论】:
标签: python memory winapi memory-management pywin32
您需要使用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"
【讨论】:
您可以在 WMI 中查询性能计数器。我做了类似的事情,但使用了磁盘空间。
一个非常有用的链接是Python WMI Tutorial by Tim Golden。
【讨论】:
您也可以直接从 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 那样有用,但绝对是一个很好的小窍门。
【讨论】:
ctype,dir(ctype) 不会有 ctype.windll,对吗?