上下文管理contextlib
contextmanager
from contextlib import contextmanager class Query(object): def __init__(self, name): self.name = name def query(self): print('Query info about %s...' % self.name)
@contextmanager
def create_query(name):
print('Begin')
q = Query(name)
try:
yield q
finally:
print('End')
with create_query("zhangsan") as zs:
zs.query()
输出
Begin
Query info about zhangsan...
End
import contextlib @contextlib.contextmanager def open_func(file_name): # __enter__方法 print('open file:', file_name, 'in __enter__') file_handler = open(file_name, 'r') # 【重点】:yield yield file_handler # __exit__方法 print('close file:', file_name, 'in __exit__') file_handler.close() return with open_func('D:/cloud/cloud-init-19.1.10/tox.ini') as file_in: for line in file_in: print(line)
cosling
返回一个在语句块执行完成时关闭 things 的上下文管理器。这基本上等价于
from contextlib import contextmanager @contextmanager def closing(thing): try: yield thing finally: thing.close()
from contextlib import closing from urllib.request import urlopen with closing(urlopen('http://www.python.org')) as page: for line in page: print(line)