环境管理器

with/as环境管理器

基本使用

with expression [as var]:
       with-block

这里expression要返回一个对象,从而支持环境管理协议。如果选用的as字句存在,此时对象也可返回一个值,赋值给var。var并非赋值为expression的结果。expression的结果是支持环境协议的对象,而var则是赋值为其他的东西。expression返回的对象可在with-block
with open('catcher.py') as myfile:
    for line in myfile:
        print(line)
这里open的调用,会返回一个文件对象,赋值给变量myfile。文件迭代器会在for循环内逐行读取。
with语句执行后,环境管理机制保证由myfile所应用的文件对象会自动关闭,即使处理该文件时,for循环引发了异常也是如此

with语句实际的工作方式

  • 计算表达式,所得到的对象称为环境管理器,必须有__enter__和__exit__方法
  • 环境管理器的__enter__方法会被调用。如果as字句存在,其返回值会赋值个as字句中的变量,否则直接丢弃
  • 代码块中嵌套的代码会执行
  • 如果with代码块引发异常,__exit__方法就会被调用,这些也是sys.exc_info返回的相同值。如果此方法返回值为假,则异常会重新引发
  • 如果with代码块没有异常,__exit__依然会被调用,其type、value以及traceback参数都会以None传递
#-*-coding:UTF-8-*-

class TraceBlock:
    def message(self,arg):
        print('running',arg)
    def __enter__(self):
        print('start with block')
        return self
    def __exit__(self,exc_type,exc_value,exc_tb):
        if exc_type is None:
            print('exited normally')
        else:
            print('raise an exception',exc_type)
            return False

if __name__ == '__main__':
    with TraceBlock() as action:
        action.message('tets')
        raise TypeError
        print('ded')
>>>
start with block
running tets
ded
exited normally

使用contextlib构造Context Manager

#coding:utf-8
from contextlib import contextmanager
@contextmanager  #装饰器 才能使用with语句 @contextmanager这个decorator接受一个generator,用yield语句把with ... as var把变量输出出去,然后,with语句就可以正常地工作了
def file_open(path):
    try:
        f_obj = open(path,'r')
        yield f_obj   #一定要有这一句不然报错
    except OSError:
        print('We had an error')
    finally:
        print('Close file')
        f_obj.close()
if __name__ == '__main__':
    with file_open('dequetest.py') as fobj:
        print(fobj.read())

contextlib.closing(thing)

可以用closing()来把该对象变为上下文对象

from contextlib import closing
from urllib.request import urlopen
if __name__ == '__main__':
    with closing(urlopen('https://www.baidu.com')) as webpage:
        for line in webpage:
            print(line)
>>>
输出百度的网页
这里的closin其实就是
@contextmanager
def closing(db):
    try:
        yield db
    except Exception:
        pass
    finally:
        db.close()
        pass

contextlib.suppress(*exceptions)

能够忽略我们想忽略的错误,下文中没有dd.txt文件,如果没有suppress语句则会报错。

from contextlib import suppress
if __name__ == '__main__':
    with suppress(FileNotFoundError):
        with open('dd.txt') as f:
            for line in f:
                print(line)

contextlib.redirect_stdout / redirect_stderr 输出流重定向

from contextlib import redirect_stdout
with open('text.txt','w') as fobj:
    with redirect_stdout(fobj):
        print('hehehhhe')
>>>在控制台中不会输出'hehehhhe',会在同一目录下生成一个文件text.txt并把'hehehhe'输出到文件中
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容