如何存档 - 文件写在__del__上打开?

时间:2014-10-24 08:22:39

标签: python memory garbage-collection destructor del

我试图在类obj破坏上做一些活动。 如何在_del__函数中打开文件? (我使用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    

4 个答案:

答案 0 :(得分:2)

正如其他人所提到的,使用____del___方法执行此类清理。相反,使用contextmanagers( with -statement)或注册atexit-handlers。

答案 1 :(得分:0)

下面的代码工作正常。

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")

在这种情况下:

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")

退出__main__函数时,在GC删除&#34; i&#34;实例(执行i .__ delete__)&#34;打开&#34;函数已从__builtins __。

中删除

答案 2 :(得分:0)

下面是我使用的替代方法 - 使用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

答案 3 :(得分:0)

问题是,正如MuSheng尝试to explain,在调用 __builtins__之前删除了__del__

您可以通过为变量指定“无”来自行触发__del__

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")
穆胜值得一些赞成,IMO