1 import contextlib 2 from queue import Queue 3 4 @contextlib.contextmanager 5 def myOpen(file): 6 f = open(file) 7 try: 8 yield f #返回f到with...as..语句中的f 9 finally: 10 f.close() 11 file = r"D: ext.txt" 12 with myOpen(file) as f: 13 #在执行这块代码时,会先执行worker_state中yield前面的代码 14 #执行完这块代码后,会执行worker_state中finally的代码 15 for line in f: 16 print(line)