如果出现任何错误后出现可见的false,Excel.exe进程将继续运行



通常我使用以下代码在后台打开excel工作簿:

import xlwings as xw
app = xw.App(visible=False)
wb = xw.Book(filename)
sheet = wb.sheets['sheet1']

当我执行包含以上行的代码(使用visible=False(时,有时我的代码不正确,并收到错误消息。在这种情况下,EXCEL.EXE进程在后台的进程列表(在windows 10上的windows任务管理器中(上保持打开状态。如果我收到错误消息,有没有一个解决方案可以在后台关闭用python代码打开的特定excel进程?否则,每当代码执行时出现错误,就会在进程列表中添加一个额外的excel进程,从而降低性能。

目前,我的解决方法是在python脚本的顶部添加以下行,但这将关闭所有excel进程:

import subprocess
subprocess.call(["taskkill", "/f", "/im", "EXCEL.EXE"])

我的目标是只关闭用python脚本打开的那个特定进程。

我在这里找到了这个代码片段。使用这个psutil库,它可以获取您正在运行的所有进程,检查进程中是否有字符串(如Adobe、EXCEL(并终止这些进程。使用Python 3和Windows 10杀死Excel会话效果很好,这些会话在我打开后继续在后台运行;闭合的";他们与Win32com。

import psutil
def main():
'''Process kill function'''    
for proc in psutil.process_iter():
# check whether the process name matches
# print(proc.name())
if any(procstr in proc.name() for procstr in
['Adobe', 'EXCEL']):
print(f'Killing {proc.name()}')
proc.kill()

if __name__ == "__main__":
main()

首选解决方案
xlwings在v0.24.3中为此问题添加了一个解决方案:
[Enhancement]xlwings。应用程序((现在可以用作上下文管理器,确保Windows上没有僵尸进程,即使您使用了隐藏的实例并且代码失败。因此,建议您尽可能使用它,如下所示:

import xlwings as xw
with xw.App(visible=False) as app:
wb = xw.Book("test.xlsx")
sheet = wb.sheets['sheet1']
# To evoke an error, I try to call an non-exisiting sheet here.
nonexistent_sheet["A1"]

with行防止EXCEL.EXE进程在windows任务管理器中保持打开状态,即使代码中有错误。

v24.0.3
之前的解决方案不太优雅:except块会捕获错误,这意味着脚本的主要目的应该写在try块中。

import xlwings as xw
import traceback
app = xw.App(visible=False)
wb = xw.Book("test.xlsx")
sheet = wb.sheets['sheet1']
# Do what you want here. To evoke an error, I try to call an non-exisiting sheet here.
try:
not_existing_sheet["A1"]
# Sources for except block: https://stackoverflow.com/a/31609619/13968392 and https://stackoverflow.com/a/54396161/13968392
except BaseException:
print(traceback.print_exc())
app.quit()

最新更新