Python异常中的行号

roo*_*oot 1 python exception

如何获取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)

  • 虽然此代码可以提供问题的解决方案,但最好添加有关其工作原理/原因的上下文。这可以帮助未来的用户学习并最终将这些知识应用到他们自己的代码中。当代码得到解释时,您也可能会得到用户的积极反馈/支持。 (6认同)