Pywin32 COM not able to set attribute keyerror

Question:

I’m trying to automate something using its com interface. There are some problems which I can’t get my head around.

app = DispatchEx('CANoe.Application')
configs = app.Configuration.TestConfigurations
config = configs.Item(1)
unit = config.TestUnits.Item(1)
unit.Name
unit.Enabled

Until here it is fine, name and enabled will print out a string and a bool value. But as soon when I want to set the enabled to false or true I get the following:

>>> unit.Enabled = False
Traceback (most recent call last):
  File "C:PythonPython310libsite-packageswin32comclient__init__.py", line 590, in __setattr__
    args, defArgs = self._prop_map_put_[attr]
KeyError: 'Enabled'

During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:PythonPython310libsite-packageswin32comclient__init__.py", line 592, in __setattr__
        raise AttributeError(
    AttributeError: '<win32com.gen_py.CANoe 12.0 Type Library.ITestUnit instance at 0x1977650030784>' object has no attribute 'Enabled'

Which is odd because in VBS it works without any problem (I need to port these to Python). Also it looks like that some attributes are not there like "Elements" when I print the internals of the unit object:

>>> print(dir(unit))
['Application', 'CLSID', 'Enabled', 'Name', 'Parent', 'Report', 'Verdict', '_ApplyTypes_', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_good_object_', '_get_good_single_object_', '_oleobj_', '_prop_map_get_', '_prop_map_put_', 'coclass_clsid']
>>>

When I do a "prop_map_put"

>>> print(unit._prop_map_put_)
{}
>>>

I tried to use setattr to set Enabled on true, it didn’t throw an exception but after that I was not able to call unit.Enabled because I need to do something with ApplyTypes.

Asked By: John

||

Answers:

To solve this issue I had to cast the tu variable to an ITestUnit3. That way i’m able to set enable.

unit = win32com.client.CastTo(unit, 'ITestUnit3')
Answered By: John
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.