在一些除了块之外我正在释放资源(应该无异常地释放),但该资源的释放函数使用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'>