[英]Python: clean way to set variable to None when not used anymore?
Using excel from Python require to set all references to workbooks & excel app to None at the end to be sure it closes (using the API win32com.client).使用 Python 中的 excel 需要在最后将对工作簿和 excel 应用程序的所有引用设置为无,以确保它关闭(使用 API win32com.client)。
At first I expected to be able to use the with
keyword and include all the "clean up" code in the __exit__()
function. But I still have references that needs to be cleaned up when I do it this way...起初我希望能够使用
with
关键字并将所有“清理”代码包含在__exit__()
function 中。但是当我这样做时,我仍然有需要清理的引用......
==> Is it possible to do it in a better way? ==> 是否有可能以更好的方式做到这一点? Better = all the clean up code in packaged in the exit () function. (not using contextmanager has the same issue: Excel doesn't close if I use the "with" keyword instead of "inline" python )
Better = exit () function 中打包的所有清理代码。(不使用 contextmanager 有同样的问题: 如果我使用“with”关键字而不是“inline”Excel 不会关闭 python )
example: I have to set wb & xlapp to None
outside for the __exit__()
function示例:对于
__exit__()
function,我必须将 wb & xlapp 设置为None
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
thanks谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.