首页 > 编程语言 > 详细

python的上下文管理器

时间:2020-07-13 12:55:58      阅读:59      评论:0      收藏:0      [点我收藏+]
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)

python的上下文管理器

原文:https://www.cnblogs.com/Ghostant/p/13292235.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!