- 在python中,读写文件这样的资源,必须在使用完毕后正确关闭他们,正确关闭文件资源的一个方法是使用
try:
f = open('/path/to/file', 'r')
f.read()
finally:
if f:
f.close()
- 写“try…finally”非常繁琐,python的with语句允许我们非常方便的使用资源,而不用担心资源没有关闭
with open('/path/to/file', 'r') as f:
f.read()
- 并不是只用open()函数返回的fp对象才能使用with语句,实际上,任何对象,只要正确实现了上下文管理,就可以用于with语句
- 实现上下文管理是通过__enter__和__exit__这两个方法来实现的,即可以理解为:同时包含__enter__和__exit__这两个方法的对象就是上下文管理器
- enter(self): 当with开始运行的时候触发此方法的运行
- exit(self, exc_type, exc_value, traceback): 当with运行结束之后触发此方法的运行
- 后面三个参数表示捕捉异常的类型、值、异常回溯的位置,是必须的参数
- 当有异常错误时exc_type为true,否则为false
class Query(object):
def __init__(self, name):
self.name = name
def __enter__(self):
print('Begin')
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
print('Error')
else:
print('End')
def query(self):
print('Query info about %s...' % self.name)
# 这样我们就可以把自己写的资源对象用于with语句:
with Query('Bob') as q:
q.query()
@contextmanager
- 编写__enter__和__exit__比较繁琐,因此python的标准库contextlib提供了更简单的写法,上面的代码可以改写如下: (contextlib-上下文库)
- @contextmanager这个decorator接受一个generator,用yield语句把with…as var 把变量输出出去,然后with语句就可以正常工作了 (contextmanager-上下文管理器 decorator-装饰器 generator-生成器 yield-量产)
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)
yield q
print('End')
with create_query('Bob') as q:
q.query()
- @contextmanager也可以实现在某段代码执行前后自送执行特定代码
@contextmanager
def tag(name):
print("<%s>" % name)
yield
print("</%s>" % name)
with tag("h1"):
print("hello")
print("world")
-
执行顺序为
- with语句首先执行yield之前的语句,打印出
- yield调用会执行with语句内部的所有语句,因此打印出hello和world
- 最后执行yield之后的语句,打印出
-
因此,@contextmanager让我们通过编写generator来简化上下文管理
@closing -
如果一个对象没有实现上下文,我们就不能把它用于with语句,这个时候,可以用closing来把对象变为上下文对象 (closing-)
- 例如,用with语句使用urlopen()
from contextlib import closing
from urllib.request import urlopen
with 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()
- closing的作用是把惹你对象变成上下文对象,并支持with语句