COM:excelApplication.Application.Quit()保留进程 [英] COM: excelApplication.Application.Quit() preserves the process

查看:206
本文介绍了COM:excelApplication.Application.Quit()保留进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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')

an 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时,是否会引起问题?可能连续很多(几打)次?我担心的是会创建冲突版本的文档等。还是为了安全起见,我应该只是每次都终止 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的任何异常和其他任何东西(或者我在这里做些破烂的事?)。我对区分不存在的进程杀死尝试和终止进程的失败尝试特别感兴趣。

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()保留进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆