[python-win32] pythoncom, multithreading, Word

Cédric Delfosse cedric.delfosse@freealter.com
05 Jun 2002 15:54:01 +0200


Hello,

I'm writing a little server to convert MSWord document (windows 2000 pro
with msoffice 2000 premium), using the ThreadingTCPServer class of
python.

In the handle part of my BaseRequestHandler, I do something like this: 

        pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) 
        w = win32com.client.Dispatch('Word.Application') 
        w.Visible = 0 
        w.DisplayAlerts = 0 
w.Documents.Open( FileName = filenamein ) 
        wc = win32com.client.constants 
        w.ActiveDocument.SaveAs( FileName = filenameout, FileFormat =
wc.wdFormatHTML ) 
        w.Documents.Close(wc.wdDoNotSaveChanges) 
        w.Quit() 
        w = None 

It works fine, except when multiple threads are making COM call in the
same time. There I'm getting lots of exception, telling me that my call
are discarded.

I don't understand why (my COM knowledge is very basic and I didn't read
the python/win32 book).

I have found a site at http://ecpspooler.sourceforge.net/, where the guy
propose a spooler to pipe COM in a queue, because:

"""

The problem, Microsoft Word can be automated externally to generate
documents. It is, however, a single use COM server which means only a
single instance can run at a time. If two programs try to generate Word
documents at the same time they will, at best, write text back and forth
into the same document, and, at worst, crash Word all together.

"""

I'm a little perplex. If I do this in a python session:

>>> w = win32com.client.Dispatch('Word.Application')
>>> w.Documents.Open( "C:\\toto.doc" )
>>> w2 = win32com.client.Dispatch('Word.Application')
>>> w.Documents.Open( "C:\\titi.doc" )

It works fine.
So why not when I use thread ? Should I catch every COM call and redo
them when they failed ? I hope not :)

Thanks in advance for your answer.

-- 
Cédric Delfosse                                      Free&ALter Soft
152, rue de Grigy - Technopole Metz 2000                  57070 METZ
tel : 03 87 75 11 74                            fax : 03 87 75 19 26