Mindee

主要记录各种包的使用代码例子, 遇到问题的处理方式 项目记录更新全部代码

  博客园  :: 首页  :: 新随笔  ::  ::  :: 管理

Context manager, atexit

python context manager 

Context managers can be used to manage any kind of resource that needs to be acquired and released in a structured way. They are a powerful tool for managing resources and avoiding common issues like memory leaks and resource exhaustion.

class FileManager:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_value, traceback):
        self.file.close()
with FileManager('test.txt', 'w') as f:
    f.write('hello, world!')

 

If you kill the Python process that is running the code that is using a context manager, the __exit__ method of the context manager may not be called. This can result in resource leaks or other issues if the context manager is responsible for releasing resources.

However, Python does have a mechanism for dealing with this scenario called an "atexit handler". An atexit handler is a function that is registered with the Python interpreter and is automatically called when the interpreter is exiting, either normally or due to an unhandled exception. You can use an atexit handler to clean up any resources that may not have been properly released if the Python process is killed.

import atexit

class FileManager:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_value, traceback):
        self.file.close()

def cleanup():
    # Release any resources here
    pass

if __name__ == '__main__':
    file_manager = FileManager('test.txt', 'w')
    with file_manager as f:
        f.write('hello, world!')
    atexit.register(cleanup)

 

posted on 2023-02-22 02:20  Mindee  阅读(23)  评论(0)    收藏  举报