Search code examples
pythonexcelmultithreadingcom-object

Python Threading With Excel Com Object


I am trying to open a workbook using a pre-opened excel com object within a python thread. Using the below code:

from multiprocessing import Process, Queue

def open_workbook(excel,iSub_Loc,q):
    p = Process(target = open_workbook_helper, args = (excel,iSub_Loc))
    p.daemon = True
    p.start()

def open_workbook_helper(excel,iSub_Locq,):
    wb = excel.Workbooks.Open(iSub_Loc)
    ws = wb.Sheets(1)
    q.put((wb,ws))

but i get the following error

Can't pickle <type PyIDispatch'>: it's not found as __builtin__.PyIDispatch

any suggestions?


Solution

  • "multiprocessing" is not "threading" - Use from threading import Thread, Queue instead. WHat happnes is that for inter-process comunication the dtaa is serialized to make the calls to the code on the other process, and COM objects use system resources that are not serializable.

    If the operations you need to perform on your data are IOBound, just using threads will fit you. If you have code that would take advantage of multiple cores in pure Python - with sheer computation, then you can a separate process with just your data - already on Python side - not the COM objects.