[python-win32] Dynamic method creation and WMI

Christian Wyglendowski Christian.Wyglendowski at greenville.edu
Fri Dec 19 16:18:27 EST 2003


I do most of my Python coding in Pythonwin and really like the code
completion feature.  Using Python with WMI, I want to be able to call:

>>> WMIobj.MethName(args)

and have a list of possible attributes/methods pop up in Pythonwin when
I type "WMIobj."  Since running makepy does not help with this (now must
call WMIobj.ExecMethod_(method_name, args)) I thought I'd write a little
wrapper class that populates self.__dict__ with valid method names and
set the values to a lambda that calls ExecMethod with the proper method
name.  That way I get code completion and the early binding via makepy.
Here is what I have so far (incomplete and buggy as it is):

class WMIObject:
    def __init__(self, object, query, computer='.'):
        wmi = GetObject('winmgmts://%s' % computer)
        self._wmiobj = wmi.ExecQuery('select * from %s where %s' %
(object, query))[0]
        for meth in self._wmiobj.Methods_:
            newmethod = str(meth.Name)
            self.__dict__[newmethod] = lambda:
self._wmiobj.ExecMethod_(meth.Name)

Here is some output from a session in the interactive interpreter.

>>> x = WMITools.WMIObject('Win32_Process', 'Name="TIWin.exe"')
>>> x.GetOwner()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "C:\Python23\Projects\AD Tools\WMITools.py", line 18, in <lambda>
    self.__dict__[newmethod] = lambda:
self._wmiobj.ExecMethod_(meth.Name)
  File "win32com\gen_py\565783C6-CB41-11D1-8B02-00600806D9B6x0x1x2.py",
line 710, in ExecMethod_
    ret = self._oleobj_.InvokeTypes(13, LCID, 1, (9, 0), ((8, 1), (9,
49), (3, 49), (9, 49)),strMethodName, objWbemInParameters, iFlags,
objWbemNamedValueSet)
com_error: (-2147352567, 'Exception occurred.', (0, 'SWbemObjectEx',
'Generic failure ', None, 0, -2147217407), None)

It apparently calls the ExecMethod method but it chokes for some reason.
I did some googling on the exception to no avail.  Continuing in the
interpreter, here is something that is interesting, though:

>>> x.GetOwner = lambda: x._wmiobj.ExecMethod_('GetOwner')
>>> x.GetOwner()
<win32com.gen_py.Microsoft WMI Scripting V1.2 Library.ISWbemObject
instance at 0x15683256>

So how come I can do the same thing after the object is created but not
in its __init__ method?

Christian



More information about the Python-win32 mailing list