COM Objects and Threading in Python

Getting an error which reads something to the extent of “CoInitialize has not been called.” when trying to run a COM object in a thread in Python (using win32com of course)?

Give this a try to fix the error:

import pythoncom
import sys

def funcName()
  sys.coinit_flags = 0
  pythoncom.CoInitialize()
  [ COM code here... ]
  pythoncom.CoUninitialize()


It took me a bit of digging on Google as well as trial and error to get this answer. The reason this fixes the problem is because for each thread you spawn in Python which uses a COM object, each thread needs to have it’s own “workspace” for COM, thereby requiring you to initialize the COM libraries for each thread. At least that’s the high level view.. I’m sure a Python guru would have a better answer.

This entry was posted in Languages, Tips, Hacks, & Tricks and tagged , , , , , , , , . Bookmark the permalink.

2 Responses to "COM Objects and Threading in Python"

Leave a reply