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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# win32com multithreading example | |
import sys | |
import time | |
from threading import Thread | |
sys.coinit_flags = 0 # pythoncom.COINIT_MULTITHREADED == 0 | |
from pythoncom import (CoInitializeEx, CoUninitialize, | |
COINIT_MULTITHREADED, PumpWaitingMessages) | |
from win32com.client import Dispatch, WithEvents | |
# COM event handlers | |
class FirstEventHandler: | |
def OnWorkbookOpen(self, Wb): | |
print "First thread: open workbook %s" % Wb.FullName | |
class SecondEventHandler: | |
def OnWorkbookBeforeClose(self, Wb, Cancel): | |
print "Second thread: close workbook %s" % Wb.FullName | |
# main thread | |
def firstThread(): | |
client = Dispatch("Excel.Application") | |
WithEvents(client, FirstEventHandler) | |
# launch the second thread | |
thread = Thread(target=secondThread, args=(client,)) | |
thread.start() | |
# event loop 1 | |
while True: | |
PumpWaitingMessages() | |
time.sleep(0.5) | |
# other thread worker function | |
def secondThread(client): | |
CoInitializeEx(COINIT_MULTITHREADED) | |
WithEvents(client, SecondEventHandler) | |
# event loop 2 | |
while True: | |
PumpWaitingMessages() | |
time.sleep(0.5) | |
CoUninitialize() | |
if __name__ == '__main__': | |
firstThread() |
No comments:
Post a Comment