如何暂时“禁用”sys.exc_info()返回当前处理的异常?

时间:2015-12-05 12:09:51

标签: python python-3.x

在一些除了块之外我正在释放资源(应该无异常地释放),但该资源的释放函数使用sys.exc_info()。有没有办法暂时标记现在没有处理异常?我创建了只替换sys.exc_info函数的解决方案,但它看起来不太可靠。可能有更好的方式存在吗?

import sys
from contextlib import contextmanager


@contextmanager
def no_exc_info():
    f = sys.exc_info
    sys.exc_info = lambda: (None, None, None)
    try:
        yield
    finally:
        sys.exc_info = f

try:
    try:
        raise Exception()
    except:
        with no_exc_info():
            # here I want sys.exc_info to return (None, None, None)
            print('1', sys.exc_info()[0])
        raise
except:
    print('2', sys.exc_info()[0])

输出(我想要):

1 None
2 <class 'Exception'>

0 个答案:

没有答案