是否可以将其包装在Python"with"语句中?

ed9*_*928 1 python python-2.7

是否可以使用它来实现以下目标?(使用"with"关键字)

之前:

try:
    raise Exception("hello")
except Exception as e:
    print "GOT IT"
Run Code Online (Sandbox Code Playgroud)

期望的效果:

def safety():
    try:
        yield
    except Exception as e:
        print "GOT IT"

with safety():
    raise Exception("hello")
Run Code Online (Sandbox Code Playgroud)

它只是使代码更清洁.目前正在运行第二个代码段会出现错误:

Traceback (most recent call last):
  File "testing.py", line 25, in <module>
    with safety():
AttributeError: __exit__
Run Code Online (Sandbox Code Playgroud)

Mar*_*zer 7

你真是太近了!

from contextlib import contextmanager

@contextmanager
def safety():
    try:
        yield
    except Exception as e:
        print "GOT IT"

with safety():
    raise Exception("hello")
Run Code Online (Sandbox Code Playgroud)