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)
原文地址:https://www.cnblogs.com/Ghostant/p/13292235.html