[python-win32] pythoncom, multithreading, Word

Chris Miles chris@psychofx.com
Thu, 6 Jun 2002 01:23:04 +1000


You should create a Semaphore object and semaphore lock your COM calls.
Then only one thread at a time will be making a call.

CM


On Wed, Jun 05, 2002 at 03:54:01PM +0200, Cédric Delfosse wrote:
> 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
> 
> 
> 
> _______________________________________________
> Python-win32 mailing list
> Python-win32@python.org
> http://mail.python.org/mailman/listinfo/python-win32

-- 
Chris Miles
chris@psychofx.com
http://www.psychofx.com/chris/