Skip to main content
 首页 » 编程设计

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

2025年05月04日14lidabo

是否可以用它来实现下面的功能? (是否使用“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")