Python 通过traceback追溯异常信息
-
导入traceback包
import traceback
-
自定义函数
def func_3():return 1 / 0def func_2():func_3()def func_1():func_2()
-
捕捉异常
try:func_1() except Exception as e:traceback_info = traceback.format_exc()print("===traceback_info===")print(traceback_info)print("===traceback_info===")
打印追溯异常信息:
===traceback_info=== Traceback (most recent call last):File "C:\Users\15011\AppData\Local\Temp\ipykernel_15680\2442583961.py", line 13, in <module>func_1()File "C:\Users\15011\AppData\Local\Temp\ipykernel_15680\2442583961.py", line 10, in func_1func_2()File "C:\Users\15011\AppData\Local\Temp\ipykernel_15680\2442583961.py", line 6, in func_2func_3()File "C:\Users\15011\AppData\Local\Temp\ipykernel_15680\2442583961.py", line 2, in func_3return 1 / 0 ZeroDivisionError: division by zero===traceback_info===