Search code examples
pythonmultithreadingcompywinautocomtypes

Using pywinauto.top_window() hangs when using it with threads


If I create a thread that all it does is connect to some process and get its top window, then the program hangs.

I debugged it a little and it seems to get stuck in comtypes._compointer_base.from_params. This is the whole traceback:

...
-> self.top_win = self.app.top_window()
  c:\python27\lib\site-packages\pywinauto\application.py(1095)top_window()
-> backend=self.backend.name)
  c:\python27\lib\site-packages\pywinauto\findwindows.py(197)find_elements()
-> cache_enable=True)
  c:\python27\lib\site-packages\pywinauto\uia_element_info.py(272)children()
-> return self._get_elements(IUIA().tree_scope["children"], cond, cache_enable)
  c:\python27\lib\site-packages\pywinauto\uia_element_info.py(261)_get_elements()
-> ptrs_array = self._element.FindAll(tree_scope, cond)
> c:\python27\lib\site-packages\comtypes\__init__.py(970)from_param()
-> return value

after typing step in pdb, it shows this and then freezes:

(Pdb) s
--Return--
> c:\python27\lib\site-packages\comtypes\__init__.py(970)from_param()-><POINTER... 41308a0>
-> return value

It seems that the problem is in using comtypes with threads, I tried to call pythoncom.CoInitialize() in the calling thread (and also in main) but it didn't help.

What can be done here?

Thanks.


Solution

  • pywinauto==0.6.4 uses multi-threading mode (MTA) for COM objects by default. Just upgrade it by pip install -U pywinauto and check if it works for you.