本文主要是介绍调用 xlwings 创建多线程时报错 pywintypes.com_error: ( ‘应用程序调用一个已为另一线程整理的接口)解决方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
创建xlwings对象
import xlwings
def run_program():app = xw.App(visible=False)# app = xw.App(visible=False, add_book=False) # 创建不可见的 Excel 应用程序实例app.display_alerts = False # 关闭 Excel 的警报app.screen_updating = False # 关闭 Excel 的屏幕更新wb = xw.Book(rule_file)
…
当开启多线程
try:thread1=threading.Thread(target=run_program)thread1.start()except Exception as re:# check_list.writeErroLog(re)traceback.print_exc(file=open('erro_log.txt','w+'))
**
这时候报错
**
Exception in thread Thread-1:
Traceback (most recent call last):File "D:\ProgramData\Anaconda3\envs\python38\lib\threading.py", line 932, in _bootstrap_innerself.run()File "D:\ProgramData\Anaconda3\envs\python38\lib\threading.py", line 870, in runself._target(*self._args, **self._kwargs)File "XXXXXX/main.py", line 135, in run_programresult_arr = rf1.Read_FormulaValue_1(rule_file, sheet_data, sheet_name, num_rows, num_cols, first_row)File "XXXXXX", line 249, in Read_FormulaValue_1app.quit()File "D:\ProgramData\Anaconda3\envs\python38\lib\site-packages\xlwings\main.py", line 300, in quitreturn self.impl.quit()File "D:\ProgramData\Anaconda3\envs\python38\lib\site-packages\xlwings\_xlwindows.py", line 368, in quitself.xl.DisplayAlerts = FalseFile "D:\ProgramData\Anaconda3\envs\python38\lib\site-packages\xlwings\_xlwindows.py", line 107, in __setattr__return setattr(self._inner, key, value)File "D:\ProgramData\Anaconda3\envs\python38\lib\site-packages\win32com\client\__init__.py", line 595, in __setattr__self._oleobj_.Invoke(*(args + (value,) + defArgs))
pywintypes.com_error: (-2147417842, '应用程序调用一个已为另一线程整理的接口。', None, None)
需要加入pythoncom.CoInitialize(),进行初始化。
def run_program():pythoncom.CoInitialize()...其他代码
这样就能正常运行。
这篇关于调用 xlwings 创建多线程时报错 pywintypes.com_error: ( ‘应用程序调用一个已为另一线程整理的接口)解决方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!