Saturday, March 25, 2017

Python win32com multithreading

Some notes on MS COM programming in Python. It is not a well documented topic. The only really helpful source is book Python Programming On Win32. Here I explain how to run two different COM event handlers in two separate threads. Example provided implements simple interaction with Excel app. But the method is universal, and I used it for accessing ITinvest SmartCOM API.

Below you can find a gist snippet. Let's go over it.

When importing modules set sys.coinit_flags to zero. This should be done before importing all the COM-related stuff.

Working with pythoncom requires CoInitialize calls in each thread. You can set mode of initialisation using CoInitializeEx. But in the main thread this function is called silently and with mode parameter as for a single-threaded app. You can change this mode setting sys.coinit_flags to 0, which is the value of pythoncom.COINIT_MULTITHREADED constant.

Then just dispatch your server, run new thread and begin the main event loop as usual. The only difference is that dispatching server and setting an event handler is done in two separate calls.

To allow your additional event loop to run in secondThread, add CoInitializeEx and CoUninitialize calls.

No comments:

Post a Comment