如何获取Python中异常的行号?
以下代码的输出
try:
print("a" + 1)
except Exception as error_message:
print("There was an error: " + str(error_message))
Run Code Online (Sandbox Code Playgroud)
是
There was an error: can only concatenate str (not "int") to str
Run Code Online (Sandbox Code Playgroud)
但不仅仅是打印
"There was an error: " + str(error_message)
Run Code Online (Sandbox Code Playgroud)
如何像这个例子一样打印行号
try:
print("a" + 1)
except Exception as error_message and linenumber as linenumber:
print("There was an error: " + str(error_message) + ". The line where the code failed was " + str(linenumber))
Run Code Online (Sandbox Code Playgroud)
预期输出为
There was an error: can only concatenate str (not "int") to str. The line where the code failed was 2
Run Code Online (Sandbox Code Playgroud)
这对我调试项目时非常有用
小智 6
import traceback
try:
print("a" + 1)
except Exception as e:
print("There was an error: " + e.args[0] + ". The line where the code failed was " + str(traceback.extract_stack()[-1][1]))
Run Code Online (Sandbox Code Playgroud)