如果我使用“with”关键字而不是“inline”python,Excel 不会关闭

2023-12-01

我使用 python 使用 win32com.client 库刷新 Excel 中的一些电源查询表。

  • 如果我将所有内容都写为“内联”(第一个版本):Excel 正确关闭
  • 如果我使用“with”语句打开/关闭 Excel 和工作簿(第二版):Excel 进程不会关闭

==> 为什么它不做同样的事情?

==> 如何使“with”版本正常工作?

代码“内联”:Excel正确关闭:

# Start excel app
xlapp = win32.gencache.EnsureDispatch('Excel.Application')
xlapp.Visible = False
xlapp.Interactive = False
excel_constant = win32.constants

# Open workbook
file_name = str(file)
wb = xlapp.Workbooks.Open(file_name)

#Refresh power query
wb.RefreshAll()
xlapp.CalculateUntilAsyncQueriesDone()

# Close workbook
wb.Close(SaveChanges=True)
wb = None
gc.collect()

# Quit excel app
xlapp.Quit()
xlapp = None
gc.collect()

使用“with”使 Excel 进程保持活动状态

class start_excel(object):
    def __init__(self):
        pass

    def __enter__(self):
        self.xlapp = win32.gencache.EnsureDispatch('Excel.Application')
        self.xlapp.Visible = False
        self.xlapp.Interactive = False

        return self.xlapp

    def __exit__(self, *args):
        self.xlapp.Quit()
        self.xlapp = None
        gc.collect()


class open_workbook(object):
    def __init__(self, xlapp, file_name):
        self.file_name = file_name
        self.xlapp = xlapp
     
    def __enter__(self):
        self.chemin_fichier = str(self.file_name)
        self.wb = self.xlapp.Workbooks.Open(self.chemin_fichier)
        
        return self.wb
 
    def __exit__(self, *args):
        self.wb.Close(SaveChanges=True)
        self.wb = None
        gc.collect()



with start_excel() as xlapp:
    # excel_constant = win32.constants
    with open_workbook(xlapp, file) as wb:
        wb.RefreshAll()
        xlapp.CalculateUntilAsyncQueriesDone()

编辑:第三个示例,带有 contextlib.contextmanager (同样的问题)

import contextlib

@contextlib.contextmanager
def start_excel():
    try:
        xlapp = win32.gencache.EnsureDispatch('Excel.Application')
        xlapp.Visible = False
        xlapp.Interactive = False
        yield xlapp

    finally:
        xlapp.Quit()
        xlapp = None
        gc.collect()

@contextlib.contextmanager
def open_workbook(xlapp, file_name):
    try:
        chemin_fichier = str(file_name)
        wb = xlapp.Workbooks.Open(chemin_fichier)
        yield wb
    
    finally:
        wb.Close(SaveChanges=True)
        wb = None
        gc.collect()



with start_excel() as xlapp:
    # excel_constant = win32.constants
    with open_workbook(xlapp, file) as wb:
        wb.RefreshAll()
        xlapp.CalculateUntilAsyncQueriesDone()

编辑:下面的代码可以工作但不令人满意我添加了最后两行:wb = None & xlapp = None,Excel 正确关闭。 但感觉不安全,有没有办法确保 with 语句干净地清除其变量?我觉得每次使用 with 时很容易忘记包含这些附加行。

class start_excel(object):
    def __init__(self):
        pass

    def __enter__(self):
        self.xlapp = win32.gencache.EnsureDispatch('Excel.Application')
        self.xlapp.Visible = False
        self.xlapp.Interactive = False

        return self.xlapp

    def __exit__(self, *args):
        self.xlapp.Quit()
        self.xlapp = None
        gc.collect()


class open_workbook(object):
    def __init__(self, xlapp, file_name):
        self.file_name = file_name
        self.xlapp = xlapp
     
    def __enter__(self):
        self.chemin_fichier = str(self.file_name)
        self.wb = self.xlapp.Workbooks.Open(self.chemin_fichier)
        
        return self.wb
 
    def __exit__(self, *args):
        self.wb.Close(SaveChanges=True)
        self.wb = None
        gc.collect()



with start_excel() as xlapp:
    # excel_constant = win32.constants
    with open_workbook(xlapp, file) as wb:
        wb.RefreshAll()
        xlapp.CalculateUntilAsyncQueriesDone()
        wb = None
    
    xlapp = None

我理解了这个问题:

  • Excel 需要将变量设置为 None 才能关闭
  • 使用 with 关键字,有 2 个引用:生成器中的引用和“主”代码中的引用。这__exit__部分仅删除 2 个引用之一。

最后一个版本按预期工作,但我不喜欢您需要在外部进行一些强制清理__exit__ part.

class start_excel(object):
    def __init__(self):
        pass

    def __enter__(self):
        self.xlapp = win32.gencache.EnsureDispatch('Excel.Application')
        self.xlapp.Visible = False
        self.xlapp.Interactive = False

        return self.xlapp

    def __exit__(self, *args):
        self.xlapp.Quit()
        self.xlapp = None
        gc.collect()


class open_workbook(object):
    def __init__(self, xlapp, file_name):
        self.file_name = file_name
        self.xlapp = xlapp
     
    def __enter__(self):
        self.chemin_fichier = str(self.file_name)
        self.wb = self.xlapp.Workbooks.Open(self.chemin_fichier)
        
        return self.wb
 
    def __exit__(self, *args):
        self.wb.Close(SaveChanges=True)
        self.wb = None
        gc.collect()



with start_excel() as xlapp:
    # excel_constant = win32.constants
    with open_workbook(xlapp, file) as wb:
        wb.RefreshAll()
        xlapp.CalculateUntilAsyncQueriesDone()
        wb = None
    
    xlapp = None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果我使用“with”关键字而不是“inline”python,Excel 不会关闭 的相关文章

随机推荐

  • Perl 正则表达式匹配具有特殊字符的字符串

    我有一个子字符串列表 需要在 URL 字符串列表中进行匹配 子字符串具有特殊字符 如 等 如果 URL 字符串包含该子字符串 我需要执行一些操作 但现在我们只说我将在控制台中打印 TRUE 我通过首先读取子字符串列表并将其放入哈希中来做到这
  • 将数据框中的字符串转换为双精度

    我使用构建了一个数据框concat它产生一个字符串 import sqlContext implicits val df sc parallelize Seq 1 0 2 0 3 0 4 0 toDF k v df registerTemp
  • 如何在 iPhone 中修剪音频文件?

    我的文档目录文件夹中有声音文件 我想修剪该声音文件 怎么做 您可以使用扩展音频文件服务 查看 ExtAudioFileRead 和 ExtAudioFileWrite 的参考 它们有示例代码 然后您可以打开一个音频文件读取它 修剪它 然后写
  • Excel 自动化 Windows 服务

    我有一个运行的 Windows 服务Excel Interop以便自动执行各种宏 然而 当我尝试时遇到了一个特殊的问题运行使用 Windows 身份验证访问数据库的宏 如果宏运行通过Windows服务 工作簿已打开 宏已开始执行 但应用程序
  • 即使我的字体是从文件创建的,为什么我必须调用 GraphicsEnvorinment.registerFont() ?

    我正在开发一个使用 JFreeChart 来呈现图表的 Web 应用程序 但是 当服务器没有安装任何中文字体时 即使我设置了字体 JFreeChart也不会显示中文字符 然后我写了一个小测试代码 发现在绘制图表之前添加这行代码可以解决问题
  • 从 Spring 和 Tomcat 中的索引页面重定向

    我有一个 Spring 应用程序 它在 Tomcat 上运行 位于 http example com foo DisplatcherServlet映射到app 例如index页面为 http example com foo app inde
  • ggplot2 中的 geom_map 边框

    我正在尝试使用 ggplot2 中的 geom map 生成分区统计图 我想用黑色或其他颜色勾勒出各个区域 以区分渐变上颜色相似的区域 使用以下代码 我尝试设置颜色来勾勒出这些区域 该代码生成地图 但没有边框 当我将颜色命令移至美学中时 它
  • 动态添加的表单元素在 IE 9 中不会被发布

    我有一个用于进行测试的表格 用户输入问题并提供问题类型和答案选项并保存问题 问题在于 当用户编写一个选项并单击 添加到选项 按钮时 选项文本框的内容将添加到 DOM 以显示为问题的答案 这一切都运行良好 直到 IE9 出现为止 当用户单击
  • 使用 ember.js 重新加载非动态路由模型的正确方法是什么?

    我有一个简单的模型数组 它们显示在列表中 路径 things 模型从 REST API 加载 在嵌套路由中 我具有添加新模型的功能 路径 things add 新模型通过 REST API 进行持久化 添加新模型后 我做了一个transit
  • 在 link_to 调用中嵌入额外的 HTML

    如何在 link to 调用中嵌入额外的 HTML 这是我想要的结果 a href exercies show 1 i class icon show i Show a 这是我的通话链接 html safe 是必需的 这样它就不会被转义
  • JavaFX:将 TextProperty(例如标签)绑定到简单的整数

    一般问题 当简单整数的值发生变化时 有没有办法更新标签 我说的是简单的整数而不是类似的东西只读整数包装器 我已经尝试了以下根据在 javafx 中将 Integer 转换为 ObservableValue 我必须将 ObservableVa
  • 类型错误:“torch.device”和“int”实例之间不支持“<”

    2023 01 25 08 21 21 659 ERROR Traceback most recent call last File home xyzUser project queue handler document queue lis
  • 更新数组 mongodb 内的嵌套数组[重复]

    这个问题在这里已经有答案了 我有以下 mongodb 文档结构 id 04 name test service 4 id 04 version 0 0 1 title testing description test protocol te
  • Google 搜索自动完成 API?

    Google 是否提供 API 访问来自动完成搜索 就像在实际网站上一样 我没能找到任何东西 我想在我自己的网站上使用 Google 的自动完成逻辑进行网络搜索 该网站依赖于 Google 的搜索 API 新的网址是 需要客户端部分 我没有
  • iPad 上仅适用于 iPhone 应用程序的空应用程序图标

    我有一个 iPhone 应用程序 该应用程序未针对在 iPad 上运行进行优化 但它包含 iPad 的所有图标 当我在 iPad 上安装应用程序时 没有图标 另外 当我在 iPad 上从商店下载应用程序时 它没有图标 在 Xcode 9 中
  • 要求/包含到变量中

    我想要求 包含一个文件并将其内容检索到变量中 test php 索引 php Like file get contents 但它仍然应该执行 PHP 代码 这可能吗 如果您包含的文件返回一个变量 包含 php
  • iOS 应用程序:Firebase 动态链接不适用于最新的 Pod 文件

    我们将最新的 Dynamic link Pod 集成到我们的 iOS 应用程序中 每当我们打开 firebase 的链接时 我们的 Appdelegate 中就不会触发任何功能 检查我们在 App delegate 中实现的方法 func
  • setSearchDisplayController 被认为是私有 API?

    我最近提交了一个应用程序进行应用程序审核 但由于使用了私有 API 而被拒绝 我对 iPhone 开发还是有点陌生 所以我想知道是否有人可以帮助我理解这部分是如何被拒绝的 UISearchBar searchBar UISearchBar
  • 身份验证令牌与 ~/.emulator_console_auth_token 不匹配

    我正在尝试通过控制台访问 android 模拟器 最初我输入telnet localhost 5554 然后我看到 接下来我输入auth auth token 我收到以下错误 这里有什么问题吗 我在哪里可以获得这个令牌 谢谢您的帮助 在 W
  • 如果我使用“with”关键字而不是“inline”python,Excel 不会关闭

    我使用 python 使用 win32com client 库刷新 Excel 中的一些电源查询表 如果我将所有内容都写为 内联 第一个版本 Excel 正确关闭 如果我使用 with 语句打开 关闭 Excel 和工作簿 第二版 Exce