python:超时后如何在单独的线程中终止 Excel 会话?

python: how to kill Excel session in separate thread after timeout?

我正在 python 中执行一个 Excel 宏,想在超时后将其终止。但是,现有的超时和 kill Excel 进程方法对我不起作用。你能帮忙吗?

import threading
import win32com.client as win;
import pythoncom;

Excel = None;
workbook = None;

def worker(e):
    global Excel;
    global workbook;

    pythoncom.CoInitialize();    
    Excel = win.DispatchEx('Excel.Application');
    Excel.DisplayAlerts = False;
    Excel.Visible = True;
    workbook = Excel.Workbooks.Open("sample.xlsm", ReadOnly = True);
    Excel.Calculation = -4135;
    print "Run";
    Excel.Run('Module2.Refresh');

e = threading.Event()
t = threading.Thread(target=worker, args=(e,));
t.start()

# wait 5 seconds for the thread to finish its work
t.join(5)
if t.is_alive():
    print "thread is not done, setting event to kill thread."
    e.set();
    print "1";
    workbook.Close();
    print "2";
    Excel.Quit();
else:
    print "thread has already finished."
    workbook.Close();
    Excel.Quit();

我收到错误:

Run
thread is not done, setting event to kill thread.
1
Traceback (most recent call last):
  File "check_odbc.py", line 62, in <module>
    workbook.Close();
  File "C:\Users\honwang\AppData\Local\conda\conda\envs\py27_32\lib\site-package
s\win32com\client\dynamic.py", line 527, in __getattr__
    raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: Open.Close

遗憾的是,无法终止线程。你所能做的就是委婉地请他们自杀,然后寄希望于最好的结果。仅传递一个事件对象是不够的,您必须主动检查线程内的事件并在设置时自杀。由于您的线程在 运行 excel 编码时被阻塞,因此它无法检查事件 - 这意味着您可以随心所欲地大喊大叫自杀,但没有代码让它听。

如果您需要这种在固有阻塞代码上的并行性,我强烈建议您改用进程,因为它们可以被终止。否则如果可能的话使用异步编程。