代码
In [2]: class Testwith():
...: def __enter__(self):
...: print("run")
...: def __exit__(self, exc_type, exc_val, ext_tb):
...: print('exit')
...:
In [3]: with Testwith():
...: print('Test is runing')
运行
with处理异常错误
代码
class Testwith():
def __enter__(self):
print("run")
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_tb is None:
print('正常结束')
else:
print('has error :%s' %exc_tb)
with Testwith():
print("Test is runing")
raise NameError('testNameError') #手动抛出错误