1

I would like to iterate over all the available properties of the object in the code below and print them. I tried print(vars(usb)), usb.dict.items() , but neither work. Is there a way to do this?

import win32com.client
wmi = win32com.client.GetObject ("winmgmts:")

for usb in wmi.InstancesOf ("Win32_PnPEntity"):
    print(usb.deviceID)
    print(usb.Availability);
    print(usb.Caption);
    ....
SEU
  • 1,304
  • 4
  • 15
  • 36

1 Answers1

1

Using dir() works on normal python objects. I'm not familiar with win32com (I'm not even using Windows), but here is a quick example:

In [1]: class Foo: 
   ...:     @property 
   ...:     def test(self): return 2 
   ...:                                                                                                                                                                                                                              

In [2]: f = Foo()                                                                                                                                                                                                                    

In [3]: dir(f)                                                                                                                                                                                                                       
Out[3]: 
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'test']

In [4]: vars(f)                                                                                                                                                                                                                      
Out[4]: {}

This should work unless the class in question is doing something unusual, like overriding __getattr__. In that case I suspect there is no way to do it, unless the library itself provides a way to do it.

EDIT: __dir__ can also be overriden and that breaks this sort of introspection. One alternative is suggested by https://stackoverflow.com/a/6886536/11939043

Vorpal
  • 306
  • 1
  • 8