使用Python获取Windows中计算机的内存使用情况
如何从运行在Windows XP上的Python中判断计算机的总体内存使用情况?您需要使用该模块。大概是这样的:使用Python获取Windows中计算机的内存使用情况,python,memory,winapi,memory-management,pywin32,Python,Memory,Winapi,Memory Management,Pywin32,如何从运行在Windows XP上的Python中判断计算机的总体内存使用情况?您需要使用该模块。大概是这样的: 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.FreePhysicalMe
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调用GlobalMemoryStatusEx()(或任何其他内核32或用户32导出):
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那样有用,但绝对是一个很好的技巧,可以放在你的后口袋里 很抱歉,这会获取总物理内存(显然)--我将保持打开状态,因为这是朝着正确方向迈出的一步,直到找到WMI命令以获取已用/可用内存。+1。更改此项以获取正确的数据将是微不足道的。@NigelHeffernan现有的答案已经使用Win32_操作系统访问免费物理内存。谢谢Michael-我应该喝更多的咖啡或回家这一次太棒了,不知道你可以在Windows中这样做。这是init的回报吗?为什么要这样做?超级调用可以省略,因为dwLength之前已经初始化过,其他字段不需要初始化。如果在unix中导入
ctype
,则dir(ctype)
将不会有ctype.windell
,对吗?