[英]how to achive - file write open on __del__?
I m trying to do a some activity on class obj destruction.我正在尝试对类 obj 销毁做一些活动。 How do I achive file open in _del__ function?如何在 _del__ 函数中打开文件? (I m using Python 3.4) (我正在使用 Python 3.4)
class iam(object):
def __init__(self):
print("I m born")
def __del__(self):
f = open("memory_report.txt", "w")
f.write("He gone safe")
f.close()
if __name__ == '__main__':
i = iam()
print("Script Ends. Now to GC clean memory")
I m born
Script Ends. Now to GC clean memory
Exception ignored in: <bound method iam.__del__ of <__main__.iam object at 0x00000000022F1A58>>
Traceback (most recent call last):
File "F:\Kumaresan\Code\Python\CommonLib\src\kmxPyQt\devConsole3\tet.py", line 14, in __del__
NameError: name 'open' is not defined
Below code is work fine.下面的代码工作正常。
class iam(object):
def __init__(self):
print("I m born")
def __del__(self):
#"open" function still in __builtins__
f = open("memory_report.txt", "w")
f.write("He gone safe")
f.close()
def write_iam():
i=iam()
if __name__ == '__main__':
write_iam()
print("Script Ends. Now to GC clean memory")
In this case:在这种情况下:
class iam(object):
def __init__(self):
print("I m born")
def __del__(self):
#__builtins__.open has remove
f = open("memory_report.txt", "w")
f.write("He gone safe")
f.close()
if __name__ == '__main__':
i = iam()
print("Script Ends. Now to GC clean memory")
When exit the __main__ function, before GC delete the "i" instance (execute i.__delete__) "open" function has remove from __builtins__.当退出 __main__ 函数时,在 GC 之前删除“i”实例(执行 i.__delete__)“open”函数已经从 __builtins__ 中移除。
As others have mentioned, don't use the ____del___ method to perform such cleanup.正如其他人所提到的,不要使用 ____del___ 方法来执行此类清理。 Instead, use either contextmanagers ( with -statement) or register atexit-handlers.相反,使用上下文管理器(带-statement)或注册 atexit-handlers。
The problem is, as MuSheng tried to explain , that the __builtins__
are removed before your __del__
is called.问题是,随着林木声试图解释,认为__builtins__
被删除您之前__del__
被调用。
You can trigger the __del__
yourself by assigning None to the variable.您可以通过将 None 分配给变量来自己触发__del__
。
MuSheng's code could be this: MuSheng的代码可能是这样的:
class iam():
def __init__(self):
print("I m born")
def __del__(self):
#"open" function still in __builtins__
with open("memory_report.txt", "w") as f:
f.write("He gone safe")
if __name__ == '__main__':
i = iam()
i = None # This triggers `__del__`
print("Script Ends. Now to GC clean memory")
MuSheng deserves some upvotes, IMO MuSheng 值得点赞,IMO
Below is an alternate I used - Using atexit handlers:下面是我使用的替代方法 - 使用 atexit 处理程序:
import atexit
class iam(object):
def __init__(self):
print("I m born")
atexit.register(self.cleanup)
def cleanup(self):
f = open("memory_report.txt", "w")
f.write("He gone safe")
f.close()
print ("Done")
if __name__ == '__main__':
i = iam()
print("Script Ends. Now to GC clean memory")
I m born
Script Ends. Now to GC clean memory
Done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.