test 1
上下文管理器,將生成器轉(zhuǎn)化為上下文管理器
import contextlib
@contextlib.contextmanager
def a():
print(1)
yield
print(3)
with a() as q:
print(2)
test 2
使用上下文管理器,抽象出異常處理
import contextlib
@contextlib.contextmanager
def b():
try:
yield
except Exception as error:
print('error:',error)
with b():
1/0
test 3
contextlib.closing 的使用時(shí),要求方法中必須存在一個(gè)close的方法名稱
import contextlib
class c:
def d(self):
print('start')
def close(self):
print('game over!')
with contextlib.closing(c()) as c_obj:
print('contextlib.close()')
test 4
with 完成多個(gè)文件的讀寫(xiě)操作
with open('a.jpg', 'rb') as from_file, open('b.jpg', 'wb') as to_file:
to_file.write(from_file.read())
?本文由簡(jiǎn)書(shū)作者:清風(fēng)Python 原創(chuàng) 如需轉(zhuǎn)載請(qǐng)注明