我正在使用 COM
集成从 Python 2.7 驱动 MS Excel.我注意到一件奇怪的事情:当我运行以下代码时:
I'm using COM
integration to drive MS Excel from Python 2.7. I noticed a peculiar thing: when I run the following bit of code:
import win32com.client
excelApp = win32com.client.dynamic.Dispatch('Excel.Application')
EXCEL.EXE
进程按预期出现在进程列表中(使用 Windows 任务管理器或 subprocess.Popen('tasklist')
查看).然后我做所有我需要做的事情没有问题.但是,当我关闭 Excel 时:
an EXCEL.EXE
process appears on the processes list (which view using the Windows Task Manager or subprocess.Popen('tasklist')
) as expected. I then do all the stuff I need to do no problem. However, when I close Excel:
excelApp.Application.Quit()
即使我关闭了启动它的 Python 解释器,该过程仍然存在(这是有道理的,因为 Excel 在不同的进程中运行,但只是为了确定).我发现终止此进程的唯一方法是手动、使用任务管理器或调用:
The process persists, even if I close the Python interpreter which started it (this kind of makes sense as Excel runs in a different process but just to be sure). The only way I've found to terminate this process is either by hand, using the Task Manager, or by calling:
subprocess.Popen("taskkill /F /im EXCEL.EXE",shell=True)
强制 /F
标志是必需的,否则进程不会终止.
the forceful /F
flag is necessary, otherwise the process doesn't terminate.
这并不是一个真正的问题(我希望如此),但我想问一下,当我第一次正常"编辑文档时,然后从 python 调用 Excel 然后再次正常"编辑文档时,这是否会导致问题?可能连续多次(几十次)?我担心的是创建相互冲突的文档版本等.还是为了安全起见,我应该每次都终止 EXCEL.EXE
进程?
This isn't really a problem (I hope) but I wanted to ask whether this could cause issues when I first edit the documents "normally", then when calling Excel from python and then "normally" again? Potentially many (couple dozens) times in a row? What I'm worried about is creating conflicting versions of documents etc. Or should I just terminate the EXCEL.EXE
process each time just to be safe?
我还注意到 subprocess.Popen("taskkill")
不会返回任何我可以 catch
和anylse 的异常(或者我在这里做了什么?).我对区分不存在的进程"终止尝试和终止进程的失败尝试特别感兴趣.
Also I noticed that subprocess.Popen("taskkill")
doesn't return any exceptions that I can catch
and anylse (or am I doing something worng here?). I'm particularly interested in distinguishing between the "non-existent process" kill attempt and a failed attempt to terminate the process.
尝试关闭所有打开的书籍,告诉应用退出并删除对应用的所有引用.我通常将我的 com 对象包装在一个类中.这就是我的退出方法的样子.
try closing any open books, telling the app to quit and delete any references to the app. I usually wrap my com objects in a class. This is what my quit method looks like.
def quit(self):
self.xlBook.Close(SaveChanges=0)
self.xlApp.Quit()
del self.xlApp
你是从主线程调用 Dispatch 吗?如果不是一定要打电话
Are you calling Dispatch from the main thread? If not be sure to call
pythoncom.CoInitialize()
发货前,
pythoncom.CoUninitialize()
退出后
这篇关于COM:excelApplication.Application.Quit() 保留进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!