【问题标题】:Get error line number Python获取错误行号 Python
【发布时间】:2016-08-24 16:04:24
【问题描述】:

我正在尝试调试 python 代码,我想指出发生错误的行号。根据asked here 找到的帖子,代码给出了被调用函数的行号。例如

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

但它给了我 foo() 的行号, 请帮助找到发生错误的确切行号。

谢谢,

【问题讨论】:

    标签: python-2.7 python-3.x


    【解决方案1】:

    在您的示例中,您必须使用他们称为 exc_tb 的 sys.exc_info() 的第三个返回值。您可以使用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])
    

    【讨论】:

      猜你喜欢
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 2018-11-14
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多