【问题标题】:Python: clean way to set variable to None when not used anymore?Python:不再使用时将变量设置为无的干净方法?
【发布时间】:2023-01-09 17:29:41
【问题描述】:

从 Python 使用 excel 需要在最后将对工作簿和 excel 应用程序的所有引用设置为 None 以确保它关闭(使用 API win32com.client)。

起初我希望能够使用 with 关键字并将所有“清理”代码包含在 __exit__() 函数中。但是当我这样做时,我仍然有需要清理的参考资料......

==> 是否有可能以更好的方式做到这一点?更好 = 所有清理代码打包在出口() 功能。 (不使用 contextmanager 有同样的问题:Excel doesn't close if I use the "with" keyword instead of "inline" python

示例:我必须将 wb & xlapp 设置为 None 外部的 __exit__() 功能

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

谢谢

【问题讨论】:

    标签: python excel-interop


    【解决方案1】:

    以此link判断,可以调用xlapp.Application.Quit()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 2018-07-18
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多