python 上下文管理器使用方法小结
上下文管理器最常用的是确保正确关闭文件, with open('/path/to/file','r') as f: f.read() with 语句的基本语法, with expression [as variable]: expression是一个上下文管理器,其实现了enter和exit两个函数。当我们调用一个with语句时, 依次执行一下步骤, 1.首先生成一个上下文管理器expression, 比如open('xx.txt'). 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()函数返回一个文件对象。 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就和我们普通的函数一样,它的原理如下: 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) 这就很方便! 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |