2016-04-29 61 views
3

我正在尝试调试python代码,我想引脚指向发生错误的行号。根据发现的帖子asked here该代码给出了被调用的函数的行号。例如获取错误行号Python

if __name__ == '__main__': 
     try: 
      foo() 
     except: 
      <the code to print line no when error occurs> 

但它给了我行没有的foo(), 请帮忙没有找到确切的行中发生错误。

感谢,

回答

1

你必须使用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]')] 

我想你正在寻找的线结构的最后一行。我还没有测试,但应该这样做:

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]) 
+0

非常感谢,它的工作。 – someone