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 

 

posted @ 2019-10-14 15:04  华为云官方博客  阅读(92)  评论(0编辑  收藏  举报