Python win32com.client 和 "with" 语句

Python win32com.client and "with" statement

下午好,

我正在使用 Python 编写一些 ETL 脚本,目前正在使用 win32com.client 打开和刷新 Excel 中的一些数据连接。

我的问题是:我是否应该使用 with 声明 open/close "Excel.Application"

import win32com.client
xl = win32com.client.DispatchEx("Excel.Application")

def wb_ref(file):
    xl.DisplayAlerts = False
    with xl.workbooks.open(file) as wb:
        wb.RefreshAll()
        wb.Save()

wb_ref('C:/Users/smugs/Documents/folder_a/workbooks/test.xlsx')

当我尝试这个时出现异常,所以我显然没有正确使用它。

Traceback (most recent call last):
  File "C:/Users/smugs/Documents/Python Scripts/Work/km_jobs/utils/xl_conv.py", line 32, in <module>
    wb_ref( 'C:/Users/smugs/Documents/folder_a/workbooks/test.xlsx')
  File "C:/Users/smugs/Documents/Python Scripts/Work/km_jobs/utils/xl_conv.py", line 11, in wb_ref
    with xl.workbooks.open(file) as wb:
AttributeError: __enter__

或者我是否需要显式调用关闭命令

def wb_ref(file):
    xl.DisplayAlerts = False
    wb = xl.workbooks.open(file)
    wb.RefreshAll()
    wb.Save()
    wb.Close()

wb_ref('C:/Users/smugs/Documents/folder_a/workbooks/test.xlsx')

第二个例子是我一直在用的,而且有效。我想我只是想知道编写上述函数的脚本的更多 pythonic 方法是什么。

(fyi - 第一次提问,长期提问 reader)

您收到 AttributeError: __enter__ 错误,因为 xl.workbooks.open 不是 context manager,因此它不支持 with 语句。

如果您想在代码中使用 with 语句,您可以使用标准库中的 closing function from the contextlib 模块,如下所示:

from contextlib import closing

def wb_ref(file):
    xl.DisplayAlerts = False
    with closing(xl.workbooks.open(file)) as wb:
        wb.RefreshAll()
        wb.Save()

contextlib.closing 将在 with 块中的代码完成执行后自动调用传递给它的对象 close