确保即使出现错误,也能运行某些清理代码。
比如:
file = open("a.py")
try:
for line in file:
if line.startswith("#"):
continue
print(line.strip())
finally:
file.close()
# 确保即使出现异常也要执行完for循环后关闭文件
with open("a.py") as file:
for line in file:
if line.startswith("#"):
continue
print(line.strip())
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
任何实现了上下文管理器协议的对象都可以用作上下文管理器。该协议包含了两个特殊方法;
enter(self):
exit(self, exc_type, exc_value, traceback):
class Con:
def __enter__(self):
print("enter")
def __exit__(self, exc_type, exc_value, trace):
print("leaving context")
if exc_type is None:
print("with no error")
else:
print("with an error (%s)" % exc_value)
模块:contextlib – 提供了与上下文管理器一起使用辅助函数
可以在一个函数里面同时提供__enter__和__exit__两部分分开,中间用yield语句分开
from contextlib import contextmanager
@contextmanager
def context():
print("enter")
try:
yield
except Exception as e:
print("leaving")
print("with an error %s", %e)
raise
else:
print("leaving")
print("with no error")