python上下文管理器細(xì)讀

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)注明

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容