Skip to content

Instantly share code, notes, and snippets.

@gbrayut gbrayut/

Last active Jan 6, 2017
What would you like to do?
Python testing WMI
#pip install comtypes wmi
import sys, os, traceback
sys.coinit_flags = 0 # sets pythoncom.COINIT_MULTITHREADED = 0
import comtypes.client #
from comtypes.automation import IDispatch, IEnumVARIANT
import wmi
#Use help(...) and dir(...) on any object/class to see more details
#These are already set on the main thread by sys package, but need to call if we use other threads
def GetMemoryUsageMB():
w = wmi.WMI('.')
result = w.query("SELECT WorkingSetPrivate FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess="+str(os.getpid()))
subset = result[0]
return float(subset.WorkingSetPrivate)/1024./1024.
print "Start %.2fMB" % GetMemoryUsageMB()
progid = "WbemScripting.SWbemLocator"
clsid = comtypes.GUID.from_progid(progid)
i = 0
while i < 100000:
i += 1
if (i % 1000 == 0):
print "%7d %.1fMB" % (i,GetMemoryUsageMB())
comtypes.CoInitializeEx(comtypes.COINIT_MULTITHREADED) #
#com_object = comtypes.client.CreateObject(progid) #
com_object = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=None) #
iface = com_object.QueryInterface(comtypes.automation.IDispatch)
#iface.Invoke() #
del iface #calls release
del com_object
except Exception, e:
print 'Exception: '+ str(e)
print traceback.format_exc()
for key in dir(iface):
method = getattr(iface,key)
if str(type(method)) == "<type 'instance'>":
print key
for sub_method in dir(method):
if not sub_method.startswith("_") and not "clsid" in sub_method.lower():
print "\t"+sub_method
print "\t",key,'=',method
print "End %.2fMB" % GetMemoryUsageMB()
#comtypes calls CoUninitialize at shutdown

This comment has been minimized.

Copy link
Owner Author

gbrayut commented Jan 5, 2017

Output on a Windows 10 system:

Start 10.92MB  
   1000 11.5MB 
   2000 11.6MB 
   3000 11.6MB 
   4000 11.6MB 
   5000 11.6MB 
 ... omitted ...
  98000 11.8MB 
  99000 11.8MB 
 100000 11.8MB 
End 11.83MB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.