New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error CoInitialize has not been called (Threading?) #759

Closed
franziferdinand opened this Issue Sep 26, 2017 · 1 comment

Comments

Projects
None yet
2 participants
@franziferdinand

franziferdinand commented Sep 26, 2017

calling

import xlwing as xw
xw.Book()

I get the following error:
Traceback (most recent call last):
File "", line 1, in
File "C:\Anaconda2\lib\site-packages\xlwings\main.py", line 479, in init
app = App(add_book=False)
File "C:\Anaconda2\lib\site-packages\xlwings\main.py", line 204, in init
self.impl = xlplatform.App(spec=spec, add_book=add_book)
File "C:\Anaconda2\lib\site-packages\xlwings_xlwindows.py", line 288, in init
self.xl = COMRetryObjectWrapper(DispatchEx('Excel.Application'))
File "C:\Anaconda2\lib\site-packages\win32com\client_init
.py", line 114, in DispatchEx
dispatch = pythoncom.CoCreateInstanceEx(clsid, None, clsctx, serverInfo, (pythoncom.IID_IDispatch,))[0]
com_error: (-2147221008, 'CoInitialize has not been called.', None, None)

Which I "solved" by adding pythoncom.CoInitialize() to the method DispatchEx in "C:\Anaconda2\lib\site-packages\win32com\client_init_.py" before calling pythoncom.CoCreateInstanceEx(...) (source)
Probably this is not the most elegant solution... Do you know anything better?

Thanks

@fzumstein

This comment has been minimized.

Member

fzumstein commented Oct 11, 2018

Fixed as long as no COM objects are passed to the thread, e.g. you can do:

import threading
from queue import Queue
import xlwings as xw

num_threads = 4


def write_to_workbook():
    while True:
        address = q.get()
        xw.Book('Book1').sheets[0].range(address).value = address
        print(address)
        q.task_done()


q = Queue()

for i in range(num_threads):
    t = threading.Thread(target=write_to_workbook)
    t.daemon = True
    t.start()

for cell in ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10']:
    q.put(cell)

q.join()

Pass around objects would be harder: https://stackoverflow.com/questions/26764978/using-win32com-with-multithreading

@fzumstein fzumstein added this to the v0.12.1 milestone Oct 11, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment