4-13 contextlib简化上下文管理器

import contextlib

@contextlib.contextmanager
def file_open(file_name):
    print("file open")
    yield {}
    print("file close")

with file_open("zhou.txt") as f:
    print("process is doing")
file open
process is doing
file close

用contextlib来修饰函数,使其变成一个上下文管理器

你可能感兴趣的:(4-13 contextlib简化上下文管理器)