上下文管理器with

import queueimport contextlib#装饰成上下文函数,上下文管理器@contextlib.contextmanagerdef worker_state(a1,a2):    a1.append(a2)#with后执行    try:        yield#回到执行语句,语句执行完毕后返回这里    finally:        a1.remove(a2)#执行q = queue.Queue()q.put("123")a1 = []a2 = "456"with worker_state(a1,a2):    print(q.get())#自定义opendef myopen(file_path,mode):    f = open(file_path,mode,encoding="utf-8")    try:        yield f#返回f,操做完成后回到这个位置    finally:        f.close()#执行closewith myopen("1.txt","a") as f:    f.write()
相关文章
相关标签/搜索