How can I tell what the computer's overall memory usage is from Python, running on Windows XP?
Asked
Active
Viewed 1.3k times
3 Answers
23
You can also just call GlobalMemoryStatusEx() (or any other kernel32 or user32 export) directly from python:
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))
Not necessarily as useful as WMI in this case, but definitely a nice trick to have in your back pocket.
-
This one was awesome, had no idea you could do this in Windows. – Anders Jun 11 '10 at 07:54
-
That's a return in __init__? Why would you do that? – Arafangion Dec 15 '11 at 03:00
-
The super call can be omitted because dwLength has been initialized before and the other _fields_ does not need to be initialized. – phobie Sep 25 '12 at 16:33
-
if i import `ctype` in unix, the `dir(ctype)` wouldn't have the `ctype.windll`, is that right? – alvas Sep 24 '13 at 09:18
13
You'll want to use the wmi module. Something like this:
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"

Michael Greene
- 10,343
- 1
- 41
- 43
-
1
-
@NigelHeffernan The existing answer already uses Win32_OperatingSystem to access FreePhysicalMemory. – Michael Greene Feb 05 '18 at 20:25
-
0
You can query the performance counters in WMI. I've done something similar but with disk space instead.
A very useful link is the Python WMI Tutorial by Tim Golden.

Skurmedel
- 21,515
- 5
- 53
- 66