我有这段代码,它将某些
Exception
转换为非致命的RuntimeWarning
:
...
for f in filter(_tty_check, [sys.stderr, sys.stdout, sys.stdin]):
cur_encoding = _tty_get_encoding(f)
if f.encoding != cur_encoding:
try:
f.reconfigure(encoding=cur_encoding) # 1. CATCH THE ERROR
except (io.UnsupportedOperation, LookupError) as err:
war = RuntimeWarning(*err.args) # 2. CONVERT IT INTO A WARNING
war.with_traceback(err.__traceback__) # 3. RESTORE TRACEBACK
if cur_encoding.startswith('x-ebcdic'):
try: f.reconfigure(encoding='cp037')
except (io.UnsupportedOperation, LookupError): pass
warnings.warn(war)
...
但是,
try...except
,然后创建警告,然后手动将垃圾粘贴到其上,这件事看起来有点尴尬和冗长。
是否有类似 warnings.filter 的opposite的东西?我想要一个指定的 errors 变为 warnings 的块,而不是指定的警告变为错误的块。
或者有没有什么方法可以将错误“投射”为警告,而无需我将回溯注入回这个笨拙的两步?
在我看来,您可以定义一个函数将异常转换为警告,例如您可以尝试在 try- except 块内除以零,或任何其他期望,它将异常转换为警告,打印它,然后继续使用剩余的代码,在我的情况下为结果设置默认值,您可以更改行为以适合您的情况。
import warnings
def convert_error_to_warning(exception):
warning = RuntimeWarning(*exception.args)
warning.with_traceback(exception.__traceback__)
return warning
try:
# Some code that may raise an exception
result = 1 / 0
except Exception as err:
warning = convert_error_to_warning(err)
# print(err) # 1
print(warning) # 2
# warnings.warn(warning) #3
# Continue with the rest of the code
result = None # Set a default value or handle the situation as needed
# Continue with the rest of the code
print("Code continues executing after the error.")
print("Result:", result)