python的上下文管理器

from contextlib import contextmanager


class Test(object):
    pass


ctx = Test()


@contextmanager
def do_with_log(log_file_path):
    try:
        ctx.log = open(log_file_path, 'w')
        yield ctx.log
    except Exception:
        pass
    finally:
        ctx.log.close()
        ctx.log = None


with do_with_log('test.txt') as log:
    log.write('123')
    print getattr(ctx, 'log', None)
print getattr(ctx, 'log', None)
posted @ 2020-07-13 11:16  GhostAnt  阅读(128)  评论(0编辑  收藏  举报