python 上下文管理器使用方法小结

时间:2021-05-22

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

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

with 语句的基本语法,

with expression [as variable]:
    with-block

expression是一个上下文管理器,其实现了enter和exit两个函数。当我们调用一个with语句时, 依次执行一下步骤,

1.首先生成一个上下文管理器expression, 比如open('xx.txt').
2.执行expression.enter()。如果指定了[as variable]说明符,将enter()的返回值赋给variable.
3.执行with-block语句块.
4.执行expression.exit(),在exit()函数中可以进行资源清理工作.

with语句不仅可以管理文件,还可以管理锁、连接等等,如,

#管理锁import threadinglock = 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

编写enter和exit仍然很繁琐,因此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.contextmanagerdef tag(name): print('<{}>'.format(name)) yield print('</{}>'.format(name))if __name__ == '__main__': with tag('h1') as t: print('hello') print('context')

管理锁

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

管理文件关闭

@contextmanagerdef 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)

管理数据库回滚

@contextmanagerdef 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 contextlibfrom urllib.request import urlopenif __name__ == '__main__': with contextlib.closing(urlopen('https://www.python.org')) as page: for line in page: print(line)closing也是一个经过@contextmanager装饰的generator,这个generator编写起来其实非常简单:@contextmanagerdef closing(thing): try: yield thing finally: thing.close()

嵌套使用

import contextlibfrom urllib.request import urlopenif __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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章