是否可以用它来实现下面的功能? (是否使用“with”关键字)
之前:
try:
raise Exception("hello")
except Exception as e:
print "GOT IT"
期望的效果:
def safety():
try:
yield
except Exception as e:
print "GOT IT"
with safety():
raise Exception("hello")
它只会让代码更简洁。当前运行第二个代码段会出现错误:
Traceback (most recent call last):
File "testing.py", line 25, in <module>
with safety():
AttributeError: __exit__
最佳答案
你离得太近了!
from contextlib import contextmanager
@contextmanager
def safety():
try:
yield
except Exception as e:
print "GOT IT"
with safety():
raise Exception("hello")
关于python - 是否可以将其包装在 Python "with"语句中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34776667/