Open instance of xlwing in another Thread (QThread)

Viewed 22

I have simple window with push button. I would like open instance of xlwings in another Thread, after click on button. But I have some error:

-pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)

I found here solution for this error, but i don't understand why I get this error without this:

import pythoncom
pythoncom.CoInitialize()

My simple window with Qthread:

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.btn = QPushButton("Open Excel")
        self.btn.clicked.connect(self.openxw)
        layout = QVBoxLayout()
        layout.addWidget(self.btn)
        self.setLayout(layout)

    def openxw(self):
        worker = MyWorker(parent = self)
        worker.start()


class MyWorker(QThread):
    sig_update_win = Signal(str)
    def __init__(self, parent = None):
        super(MyWorker, self).__init__(parent)
        self.parent = parent

    def run(self):
        book = xw.App()

Could you explain me why i need pythoncom.CoInitialize() in Multithreading?

1 Answers

In order to use any of the pythoncom library functions you first need to load/initialize the library onto your current thread. CoInitialize() does exactly this. Without calling this function you are asking your thread to use a library that it does not know exists.

Related