我经常在python异常中这样做:
try:
<some process>
except Exception as e:
print(e)
当我希望脚本继续运行但仍然告诉我有错误时,这对我有帮助。但是,print(e)
并不像我让异常引发那样详细。有什么办法可以在不引发异常的情况下更详细地显示错误?
答案 0 :(得分:2)
有多种打印回溯信息的方法。
如评论中所述,您可以使用traceback模块的print_exc函数
try:
1 / 0
except Exception:
traceback.print_exc()
Traceback (most recent call last):
File "exes.py", line 10, in <module>
1 / 0
ZeroDivisionError: division by zero
如果使用日志记录模块,则logging.exception函数将自动记录回溯,作为ERROR级别日志消息的一部分。
try:
2 / 0
except Exception:
logging.exception('Something went wrong')
ERROR:root:Something went wrong
Traceback (most recent call last):
File "exes.py", line 15, in <module>
2 / 0
ZeroDivisionError: division by zero
如果您希望以其他日志级别记录回溯,则可以将exc_info=True
传递给日志功能以记录回溯。
try:
3 / 0
except Exception:
logging.warning('Something went wrong.', exc_info=True)
WARNING:root:Something went wrong.
Traceback (most recent call last):
File "exes.py", line 20, in <module>
3 / 0
ZeroDivisionError: division by zero