Skip to content

Instantly share code, notes, and snippets.

@vlasenkov
Last active December 31, 2023 19:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save vlasenkov/f8fe40d5b2d9e43fd46ad8363067acce to your computer and use it in GitHub Desktop.
Save vlasenkov/f8fe40d5b2d9e43fd46ad8363067acce to your computer and use it in GitHub Desktop.
win32com multithreading example (python 2)
# 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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment