Skip to content

Instantly share code, notes, and snippets.

Forked from vlasenkov/
Last active July 28, 2022 05:08
What would you like to do?
win32com multithreading example
# win32com multithreading example
import sys
import time
from threading import Thread
# sys.coinit_flags has to be set before importing pythoncom and win32com, otherwise the following errors would be showing up
# - The application called an interface that was marshalled for a different thread.
# - This COM object can not automate the makepy process - please run makepy manually for this object
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,))
    # event loop 1
    while True:
# other thread worker function
def secondThread(client):
    WithEvents(client, SecondEventHandler)
    # event loop 2
    while True:
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment