【问题标题】:Is it possible to know the line on which an error occurred using try/except in Python? [duplicate]是否可以在 Python 中使用 try/except 知道发生错误的行? [复制]
【发布时间】:2016-08-05 07:08:56
【问题描述】:

例如,是否可以在以下内容中添加任何可以提供错误行号的内容?

try:
    assert False
except Exception, e:
    # lineOfError = ?
    # print lineOfError
    print e

【问题讨论】:

    标签: python exception-handling


    【解决方案1】:

    您可以使用traceback 模块:

    from sys import exc_info
    from traceback import extract_tb
    
    try:
        assert False
    except Exception as e:
        print(extract_tb(exc_info()[2])[0][1])
        print(e)
    

    【讨论】:

    • 我需要的唯一区别是添加了 [0] 索引,以便访问包含错误信息的元组:print(extract_tb(exc_info()[2])[0][1])
    • @Phillip:感谢您的关注。现在已经修好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 2017-06-26
    • 2019-04-29
    • 2018-06-18
    • 2010-10-22
    • 1970-01-01
    相关资源
    最近更新 更多