1. 程式人生 > >Python上下文管理使用

Python上下文管理使用

open log queue blog 返回 cnblogs all finally sta

 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:\text.txt"
12 with myOpen(file) as f:
13     #在執行這塊代碼時,會先執行worker_state中yield前面的代碼
14 #執行完這塊代碼後,會執行worker_state中finally的代碼 15 for line in f: 16 print(line)

Python上下文管理使用