python with语句里有raise, exit还会执行吗
测试代码
# test_raise.py
class test_context:
def __enter__(self):
print("enter")
def __exit__(self, exc_type, exc_val, exc_tb):
print("exit")
with test_context():
print("in test_context1")
raise ValueError("error!")
print("in test_context2")
运行结果
root@pve828qzz5mf6x:~/test# /usr/bin/python3.8 /root/vemu_v_link_check/test_raise.py
enter
in test_context1
exit
Traceback (most recent call last):
File "/root/test/test_raise.py", line 14, in <module>
raise ValueError("error!")
ValueError: error!
结论
会执行
扩展
python with语句里有return, exit还会执行吗
该扩展的结论:会执行,且是在return语句执行之后。