Python win32com.client 和 "with"语句

标签 python pywin32 with-statement excel.application

下午好

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

我的问题是:我应该使用 with 语句来打开/关闭“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 方式是什么。

(仅供引用 - 首次提问者,长期读者)

最佳答案

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

如果您想在代码中使用with 语句,您可以使用closing来自 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 block 中的代码完成执行时自动调用传递给它的对象的 close

关于Python win32com.client 和 "with"语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53355048/

相关文章:

javascript - With 语句的性能影响

python - Pandas mul 密集与稀疏

python - 使用 Python 访问 MS Word 2010 时出现问题

python - 如何获取 win32file 文件句柄中的当前读取位置?

python - windows:在双击标题栏时禁用最大化窗口,并在单击任务栏时最小化窗口

python - StringIO 和与 'with' 语句的兼容性(上下文管理器)

sql - 是否可以在多个更新中使用 WITH 子句而不将其复制到每个更新中?

python - Nginx:将 WordPress URL 映射到新的静态网站

python - IOError : [Errno 13] Permission denied when trying to open hidden file in "w" mode

python - return with nothing 在 python 中是什么意思?