调用 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_inner
    self.run()
  File "D:\ProgramData\Anaconda3\envs\python38\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "XXXXXX/main.py", line 135, in run_program
    result_arr = rf1.Read_FormulaValue_1(rule_file, sheet_data, sheet_name, num_rows, num_cols, first_row)
  File "XXXXXX", line 249, in Read_FormulaValue_1
    app.quit()
  File "D:\ProgramData\Anaconda3\envs\python38\lib\site-packages\xlwings\main.py", line 300, in quit
    return self.impl.quit()
  File "D:\ProgramData\Anaconda3\envs\python38\lib\site-packages\xlwings\_xlwindows.py", line 368, in quit
    self.xl.DisplayAlerts = False
  File "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()
	...其他代码

这样就能正常运行。

你可能感兴趣的:(python)