Python exception handling - line number

前端 未结 6 1265
感动是毒
感动是毒 2020-12-12 12:24

I\'m using python to evaluate some measured data. Because of many possible results it is difficult to handle or possible combinations. Sometimes an error happens during the

6条回答
  •  情书的邮戳
    2020-12-12 13:29

    To simply get the line number you can use sys, if you would like to have more, try the traceback module.

    import sys    
    try:
        [][2]
    except IndexError:
        #  Python 2
        print 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno)
        #  Python 3
        print("Error on line {}".format(sys.exc_info()[-1].tb_lineno))
    

    prints:

    Error on line 3
    

    Example from the traceback module documentation:

    import sys, traceback
    
    def lumberjack():
        bright_side_of_death()
    
    def bright_side_of_death():
        return tuple()[0]
    
    try:
        lumberjack()
    except IndexError:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print "*** print_tb:"
        traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
        print "*** print_exception:"
        traceback.print_exception(exc_type, exc_value, exc_traceback,
                                  limit=2, file=sys.stdout)
        print "*** print_exc:"
        traceback.print_exc()
        print "*** format_exc, first and last line:"
        formatted_lines = traceback.format_exc().splitlines()
        print formatted_lines[0]
        print formatted_lines[-1]
        print "*** format_exception:"
        print repr(traceback.format_exception(exc_type, exc_value,
                                              exc_traceback))
        print "*** extract_tb:"
        print repr(traceback.extract_tb(exc_traceback))
        print "*** format_tb:"
        print repr(traceback.format_tb(exc_traceback))
        print "*** tb_lineno:", exc_traceback.tb_lineno
    

提交回复
热议问题