views:

424

answers:

3

How can I tell what the computer's overall memory usage is from Python, running on Windows XP?

+3  A: 

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
I'm sorry, this gets the total physical memory (obviously) -- I'll leave open as it's a step in the right direction until I find the WMI command to get the used/free memory.
Michael Greene
+1. It will be trivial to change this to fetch the correct data.
Skurmedel
A: 

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
+4  A: 

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_uint),
                ("dwMemoryLoad", ctypes.c_uint),
                ("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 = 2*4 + 7*8     # size = 2 ints, 7 longs
        return super(MEMORYSTATUSEX, self).__init__()

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

print "dwMemoryLoad:", stat.dwMemoryLoad

Not necessarily as useful as WMI in this case, but definitely a nice trick to have in your back pocket.

Seth
This one was awesome, had no idea you could do this in Windows.
Anders