python 上下文管理器

作者: 苟雨 | 来源:发表于2017-10-09 18:53 被阅读45次

    上下文管理器最常用的是确保正确关闭文件,

    with open('/path/to/file', 'r') as f:
        f.read()
    

    with 语句的基本语法,

    with expression [as variable]:
        with-block
    

    expression是一个上下文管理器,其实现了enterexit两个函数。当我们调用一个with语句时, 依次执行一下步骤,
    1.首先生成一个上下文管理器expression, 比如open('xx.txt').
    2.执行expression.enter()。如果指定了[as variable]说明符,将enter()的返回值赋给variable.
    3.执行with-block语句块.
    4.执行expression.exit(),在exit()函数中可以进行资源清理工作.
    with语句不仅可以管理文件,还可以管理锁、连接等等,如,

    #管理锁
    import  threading
    lock = threading.lock()
    with lock:
        #执行一些操作
        pass
    
    #数据库连接管理
    def test_write():
        sql = """      #具体的sql语句
        """
        con = DBConnection()
        with con as cursor:   
            cursor.execute(sql)
            cursor.execute(sql)
            cursor.execute(sql)
    
    自定义上下文管理器

    上下文管理器就是实现了上下文协议的类 ,也就是要实现 __enter__()__exit__()两个方法。

    __enter__():主要执行一些环境准备工作,同时返回一资源对象。如果上下文管理器open("test.txt")的enter()函数返回一个文件对象。
    __exit__():完整形式为exit(type, value, traceback),这三个参数和调用sys.exec_info()函数返回值是一样的,分别为异常类型、异常信息和堆栈。如果执行体语句没有引发异常,则这三个参数均被设为None。否则,它们将包含上下文的异常信息。_exit()方法返回True或False,分别指示被引发的异常有没有被处理,如果返回False,引发的异常将会被传递出上下文。如果exit()函数内部引发了异常,则会覆盖掉执行体的中引发的异常。处理异常时,不需要重新抛出异常,只需要返回False,with语句会检测exit()返回False来处理异常。

    class test_query:
        def __init__(self):
            pass
    
        def query(self):
            print('query')
    
        def __enter__(self):
            # 如果是数据库连接就可以返回cursor对象
            # cursor = self.cursor
            # return cursor
            print('begin query,')
            return self #由于这里没有资源对象就返回对象
            
        def __exit__(self,exc_type,exc_value,traceback):
            if traceback is None:
                print('End')
            else:
                print('Error')
    
            # 如果是数据库连接提交操作
            # if traceback is None:
            #   self.commit()
            # else:
            #   self.rollback()
            
    if __name__ == '__main__':
        with test_query() as q:
            q.query()
    
    
    contextlib

    编写enterexit仍然很繁琐,因此Python的标准库contextlib提供了更简单的写法,
    基本语法

       @contextmanager
            def some_generator(<arguments>):
                <setup>
                try:
                    yield <value>
                finally:
                    <cleanup>
    

    生成器函数some_generator就和我们普通的函数一样,它的原理如下:
    some_generator函数在在yield之前的代码等同于上下文管理器中的enter函数.
    yield的返回值等同于enter函数的返回值,即如果with语句声明了as <variable>,则yield的值会赋给variable.
    然后执行<cleanup>代码块,等同于上下文管理器的exit函数。此时发生的任何异常都会再次通过yield函数返回。
    例,
    自动加括号

    import contextlib
    
    @contextlib.contextmanager
    def tag(name):
        print('<{}>'.format(name))
        yield
        print('</{}>'.format(name))
    
    
    if __name__ == '__main__':
        with tag('h1') as t:
            print('hello')
            print('context')
    
    

    管理锁

    @contextmanager
    def locked(lock):
        lock.acquire()
        try:
            yield
        finally:
            lock.release()
    
    with locked(myLock):
        #代码执行到这里时,myLock已经自动上锁
        pass
        #执行完后会,会自动释放锁
    

    管理文件关闭

    @contextmanager
    def myopen(filename, mode="r"):
        f = open(filename,mode)
        try:
            yield f
        finally:
            f.close()
    
    with myopen("test.txt") as f:
        for line in f:
            print(line)
    

    管理数据库回滚

    @contextmanager
    def transaction(db):
        db.begin()
        try:
            yield 
        except:
            db.rollback()
            raise
        else:
            db.commit()
    
    with transaction(mydb):
        mydb.cursor.execute(sql)
        mydb.cursor.execute(sql)
        mydb.cursor.execute(sql)
        mydb.cursor.execute(sql)
    

    这就很方便!
    如果一个对象没有实现上下文,我们就不能把它用于with语句。这个时候,可以用closing()来把该对象变为上下文对象。它的exit函数仅仅调用传入参数的close函数.
    例如,用with语句使用urlopen():

    import contextlib
    from urllib.request import urlopen
    
    if __name__ == '__main__':
        with contextlib.closing(urlopen('https://www.python.org')) as page:
            for line in page:
                print(line)
    

    closing也是一个经过@contextmanager装饰的generator,这个generator编写起来其实非常简单:

    @contextmanager
    def closing(thing):
        try:
            yield thing
        finally:
            thing.close()
    

    嵌套使用

    import contextlib
    from urllib.request import urlopen
    
    if __name__ == '__main__':
        with contextlib.closing(urlopen('https://www.python.org')) as page,\
                contextlib.closing(urlopen('https://www.python.org')) as p:
            for line in page:
                print(line)
                    print(p)
    

    在2.x中需要使用contextlib.nested()才能使用嵌套,3.x中可以直接使用。
    更多函数可以参考官方文档https://docs.python.org/3/library/contextlib.html

    相关文章

      网友评论

        本文标题:python 上下文管理器

        本文链接:https://www.haomeiwen.com/subject/sappyxtx.html