赞
踩
如果要在多个线程中使用win32com,需要使用CoMarshalInterThreadInterfaceInStream()和CoGetInterfaceAndReleaseStream()在线程之间传递实例,因为COMObject不能直接传递给线程:
import pythoncom, win32com.client, threading, time def start(): # Initialize pythoncom.CoInitialize() # Get instance xl = win32com.client.Dispatch('Excel.Application') # Create id xl_id = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, xl) # Pass the id to the new thread thread = threading.Thread(target=run_in_thread, kwargs={'xl_id': xl_id}) thread.start() # Wait for child to finish thread.join() def run_in_thread(xl_id): # Initialize pythoncom.CoInitialize() # Get instance from the id xl = win32com.client.Dispatch( pythoncom.CoGetInterfaceAndReleaseStream(xl_id, pythoncom.IID_IDispatch) ) time.sleep(5) if __name__ == '__main__': start()
有关详细信息,请参见:https://mail.python.org/pipermail/python-win32/2008-June/007788.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。