Python 2.1, COM (Excel), and Threads...

Stephen stephen.tubbs at
Thu Oct 31 19:31:03 CET 2002

Hi -

   I am trying to get a threaded job server running that will thread
scripts to manipulate various MS office apps.  My first attempt has
failed on Excel.  It seems that invoking
win32com.client.Dispatch('Excel.Application') from within a thread
does not initialize the same way as it does when it is called from
within the main python environment.  A simple example:

from threading import Thread

class foo:
    def run(self):
            import win32com.client
            self.excel = win32com.client.Dispatch("Excel.Application")
            self.excel.Visible = 1
            k = self.excel.Workbooks.Add()
            v = k.Worksheets(1)
            v.Cells(1,1).Value = str(self)
            import traceback

l = Thread(target = foo().run,    #creates a new instance 
                 name = 'foo',verbose = 1)

This causes the following stack trace:

Traceback (most recent call last):
  File "I:\F\P\sp\interfaces\dispatcher\", line
18, in run
    self.excel = win32com.client.Dispatch("Excel.Application")
  File "d:\python21\win32com\client\", line 94, in Dispatch
    dispatch, userName =
  File "d:\python21\win32com\client\", line 81, in
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "d:\python21\win32com\client\", line 72, in
    IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx,
com_error: (-2147221008, 'CoInitialize has not been called.', None,

Is there an alternate initialization procedure that will work from
within a Thread?

Any help would be greatly appreciated.


More information about the Python-list mailing list