how to achive - file write open on __del__?

 ̄綄美尐妖づ 提交于 2019-12-02 04:43:07
deets

As others have mentioned, don't use the ____del___ method to perform such cleanup. Instead, use either contextmanagers (with-statement) or register atexit-handlers.

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__.

Below is an alternate I used - Using atexit handlers:

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

Output:

I m born
Script Ends. Now to GC clean memory
Done
GUI Junkie

The problem is, as MuSheng tried to explain, that the __builtins__ are removed before your __del__ is called.

You can trigger the __del__ yourself by assigning None to the variable.

MuSheng's code could be this:

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!