som*_*one 5 python-2.7 python-3.x
我正在尝试调试 python 代码,我想指出发生错误的行号。根据此处询问的帖子,代码给出了被调用函数的行号。例如
if __name__ == '__main__':
try:
foo()
except:
<the code to print line no when error occurs>
Run Code Online (Sandbox Code Playgroud)
但它给了我 foo() 的行号,请帮助找到发生错误的确切行号。
谢谢,
您必须使用 sys.exc_info() 的第三个返回值,它们在您的示例中称为 exc_tb 。您可以使用traceback.extract_tb (exc_tb)浏览回溯对象,而不是使用exc_tb.tb_lineno 。代表看起来像:
*** extract_tb:
[('<doctest...>', 10, '<module>', 'lumberjack()'),
('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
Run Code Online (Sandbox Code Playgroud)
我想您正在寻找的行是结构的最后一行。我还没有测试过,但这应该可以:
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])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4689 次 |
| 最近记录: |