xlwings 在使用线程时未正确更新全局变量

问题描述 投票:0回答:1

这是我试图理解的逻辑。

import xlwings as xw
import threading
workbook = ""

def function1():
    t1 = threading.Thread(target=function2)
    t1.start()
    t1.join()

def function2():
    global workbook
    workbook = xw.Book()

function1()
print (workbook)

当我运行以下命令时,我收到以下消息:

Traceback (most recent call last):
  File "c:\Users\rakesh.ramanjulu\Documents\Python Projects\Vendor ScoreCard Accuracy Final\test.py", line 51, in <module>
    print (workbook)
  File "C:\Users\rakesh.ramanjulu\AppData\Local\Programs\Python\Python312\Lib\site-packages\xlwings\main.py", line 1288, in __repr__
    return "<Book [{0}]>".format(self.name)
                                 ^^^^^^^^^
  File "C:\Users\rakesh.ramanjulu\AppData\Local\Programs\Python\Python312\Lib\site-packages\xlwings\main.py", line 1105, in name
    return self.impl.name
           ^^^^^^^^^^^^^^
  File "C:\Users\rakesh.ramanjulu\AppData\Local\Programs\Python\Python312\Lib\site-packages\xlwings\_xlwindows.py", line 837, in name
    return self.xl.Name
           ^^^^^^^^^^^^
  File "C:\Users\rakesh.ramanjulu\AppData\Local\Programs\Python\Python312\Lib\site-packages\xlwings\_xlwindows.py", line 199, in __getattr__
    v = getattr(self._inner, item)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\rakesh.ramanjulu\AppData\Local\Programs\Python\Python312\Lib\site-packages\xlwings\_win32patch.py", line 55, in __getattr__
    return getattr(d, attr)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\rakesh.ramanjulu\AppData\Local\Programs\Python\Python312\Lib\site-packages\win32com\client\__init__.py", line 585, in __getattr__
    return self._ApplyTypes_(*args)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\rakesh.ramanjulu\AppData\Local\Programs\Python\Python312\Lib\site-packages\win32com\client\__init__.py", line 574, in _ApplyTypes_
    self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pywintypes.com_error: (-2147220995, 'Object is not connected to server', None, None)

我有点困惑为什么会发生这种情况。通过线程更新全局变量从未给我带来问题,但不确定是否能解决上述情况。我假设变量会改变,但不会。

python global-variables global xlwings
1个回答
0
投票

详细说明我的 mac 上发生的情况:

如果我允许 xw.Book() 启动 Excel 应用程序,我就得到了

enter image description here

如果我事先启动 Excel(不创建工作簿,只是启动应用程序),您的代码可以正常工作: enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.