我正在尝试调试 python 代码,我想指出发生错误的行号。根据找到的帖子asked here代码给出了被调用函数的行号。例如
if __name__ == '__main__':
try:
foo()
except:
<the code to print line no when error occurs>
但它给了我 foo() 的行号,
请帮助找到发生错误的确切行号。
谢谢,
最佳答案
您必须使用他们在您的示例中调用 exc_tb 的 sys.exc_info() 的第三个返回值。您可以使用 traceback.extract_tb 浏览回溯对象,而不是使用 exc_tb.tb_lineno (exc_tb)。代表看起来像:
*** extract_tb:
[('<doctest...>', 10, '<module>', 'lumberjack()'),
('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
我想您正在寻找的行是结构的最后一行。我还没有测试过,但这应该可以:
import sys, os, traceback
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
tb = traceback.extract_tb(exc_tb)[-1]
print(exc_type, tb[2], tb[1])
关于python-2.7 - 获取错误行号 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36939266/