如何提取 python 错误输出的信息
How to extract information for python error output
我正在尝试提取我正在编写的代码的信息。例如,当我写这段代码时:
code = "hello"
code[10]
我将从 python 得到的输出如下:
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_24520/526779498.py in <module>
----> 1 code[10]
IndexError: string index out of range
但是当我在代码上实现 try except 循环时:
code = "hello"
try:
code[10]
except Exception as e:
print(e)
我的输出只显示我:
string index out of range
我需要做什么才能提取文本“IndexError”。此外,如果有任何库可用于提取 python 错误以进行日志记录,请也让我知道。谢谢。
您需要获取异常的名称属性
code = "hello"
try:
code[10]
except Exception as e:
print(type(e).__name__)
输出:
IndexError
要获得完整的回溯,您可以像这样使用 traceback
import traceback
code = "hello"
try:
code[10]
except Exception:
print(traceback.format_exc())
我正在尝试提取我正在编写的代码的信息。例如,当我写这段代码时:
code = "hello"
code[10]
我将从 python 得到的输出如下:
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_24520/526779498.py in <module>
----> 1 code[10]
IndexError: string index out of range
但是当我在代码上实现 try except 循环时:
code = "hello"
try:
code[10]
except Exception as e:
print(e)
我的输出只显示我:
string index out of range
我需要做什么才能提取文本“IndexError”。此外,如果有任何库可用于提取 python 错误以进行日志记录,请也让我知道。谢谢。
您需要获取异常的名称属性
code = "hello"
try:
code[10]
except Exception as e:
print(type(e).__name__)
输出:
IndexError
要获得完整的回溯,您可以像这样使用 traceback
import traceback
code = "hello"
try:
code[10]
except Exception:
print(traceback.format_exc())