Skip to content


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.

Posted in Python.

2 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Burke said

    Brandon - this post saved my life, and was the first hit I got on Google when I went searching for an answer. Nice. Thanks!

  2. Colin said

    Yes, this post is definitely a life saver. Python make COM really easy so long as everything is working. Once something breaks my COM ignorance can no longer be ignored.

    One question: what does the ’sys.coinit_flags = 0′ call do?

    Thanks.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.