0
点赞
收藏
分享

微信扫一扫

python上下文管理器细读

IT影子 2021-09-26 阅读 45

test 1

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

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 open('a.jpg', 'rb') as from_file, open('b.jpg', 'wb') as to_file:
    to_file.write(from_file.read())

©本文由简书作者:清风Python 原创 如需转载请注明

举报

相关推荐

0 条评论