Python 2.1, COM (Excel), and Threads...
Mark Hammond
mhammond at skippinet.com.au
Thu Oct 31 19:03:27 EST 2002
Adam Karpierz wrote:
> # You have to use pythoncom.CoInitialize and pythoncom.CoUninitialize eg.:
For all threads other than the main thread, correct.
>
> import pythoncom
> pythoncom.CoInitialize()
>
>
>> self.excel = win32com.client.Dispatch("Excel.Application")
>
>
> pythoncom.CoUninitialize()
>
>
>> self.excel.Visible = 1
>> k = self.excel.Workbooks.Add()
>> v = k.Worksheets(1)
>> v.Cells(1,1).Value = str(self)
>> except:
>> import traceback
>> traceback.print_exc()
>
This is wrong though. It should look more like:
import pythoncom
pythoncom.CoInitialize()
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)
# Remove all refs, then uninit.
self.excel = None
k = v = None
pythoncom.CoUninitialize()
ie, CoUninitialize should be the last thing done on a thread, and only
done after all references to objects created on that thread have been
destroyed.
Storing a thread-created COM object in your instance (ie, self.excel) is
a recipe for disaster, but I haven't time to go there now!
Mark.
More information about the Python-list
mailing list