环境管理器

2017-05-14  本文已影响24人  低吟浅唱1990

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语句实际的工作方式

#-*-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'输出到文件中
上一篇 下一篇

猜你喜欢

热点阅读