Python:超时后如何在单独的线程中杀死Excel会话?

时间:2018-08-07 04:19:57

标签: python pywin32

我正在python中执行Excel宏,想在超时后将其杀死。但是,现有的超时和终止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

1 个答案:

答案 0 :(得分:1)

不幸的是,无法杀死线程。您所能做的就是很好地请他们自杀,然后希望最好。仅传递事件对象是不够的,您必须主动检查线程中的该事件,并在设置事件时自杀。由于您的线程在运行excel代码时被阻止,因此无法检查该事件-这意味着您可以大声喊叫自己自杀,但是没有任何代码可以让它监听。

如果在固有的阻塞代码上需要这种并行性,我强烈建议您改用进程,因为这些进程可能会被杀死。否则,请尽可能使用异步编程。