Python上下文管理
1 import queue 2 import contextlib 3 import time 4 @contextlib.contextmanager 5 def worker_state(xxx,val): 6 xxx.append(val) 7 print("before",xxx) 8 try: 9 time.sleep(1) 10 yield 11 finally: 12 xxx.remove(val) 13 print("after",xxx) 14 15 if __name__ == '__main__': 16 q = queue.Queue() 17 q.put("123") 18 li = [] 19 with worker_state(li,1): 20 q.get()
1 C:\Python35\python3.exe F:/Python/taochen/day22/a15.py 2 before [1] 3 after [] 4 5 Process finished with exit code 0