如何获取详细异常?

How to get detailed exception?

我经常在 python 异常中这样做:

try:
    <some process>
except Exception as e:
    print(e)

当我希望脚本继续运行但仍然告诉我有错误时,这对我很有帮助。但是,print(e) 并不像我引发异常那样详细。有没有办法在不引发异常的情况下更详细地显示错误?

有多种方法可以打印回溯信息。

如评论中所述,可以使用traceback module's 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 函数将自动将回溯记录为错误级别日志消息的一部分。

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