import queue
import contextlib
#装饰成上下文函数,上下文管理器
@contextlib.contextmanager
def 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())
#自定义open
def myopen(file_path,mode):
f = open(file_path,mode,encoding="utf-8")
try:
yield f#返回f,操作完成后回到这个位置
finally:
f.close()#执行close
with myopen("1.txt","a") as f:
f.write()