python上下文管理器细读

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

contextlib.closing 的使用时,要求方法中必须存在一个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 完成多个文件的读写操作

with open('a.jpg', 'rb') as from_file, open('b.jpg', 'wb') as to_file:
    to_file.write(from_file.read())

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容