Python异常处理——行号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14519177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:42:27  来源:igfitidea点击:

Python exception handling - line number

pythonexceptionindexing

提问by JeCh

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 evaluation. It is usually an index error because I get out of range from measured data.

我正在使用 python 来评估一些测量数据。由于许多可能的结果很难处理或可能的组合。有时在评估过程中会发生错误。这通常是索引错误,因为我超出了测量数据的范围。

It is very difficult to find out on which place in code the problem happened. It would help a lot if I knew on which line the error was raised. If I use following code:

很难找出问题发生在代码中的哪个位置。如果我知道错误发生在哪一行,那将会有很大帮助。如果我使用以下代码:

try:
    result = evaluateData(data)
except Exception, err:
    print ("Error: %s.\n" % str(err))

Unfortunately this only tells me that there is and index error. I would like to know more details about the exception (line in code, variable etc.) to find out what happened. Is it possible?

不幸的是,这只告诉我存在索引错误。我想了解有关异常的更多详细信息(代码行、变量等)以了解发生了什么。是否可以?

Thank you.

谢谢你。

回答by root

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

要简单地获取您可以使用的行号sys,如果您想要更多,请尝试回溯模块。

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 tracebackmodule documentation:

traceback模块文档中的示例

import sys, traceback

def lumberHyman():
    bright_side_of_death()

def bright_side_of_death():
    return tuple()[0]

try:
    lumberHyman()
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

回答by Apogentus

Solution, printing filename, linenumber, line itself and exception descrition:

解决方案,打印文件名、行号、行本身和异常描述:

import linecache
import sys

def PrintException():
    exc_type, exc_obj, tb = sys.exc_info()
    f = tb.tb_frame
    lineno = tb.tb_lineno
    filename = f.f_code.co_filename
    linecache.checkcache(filename)
    line = linecache.getline(filename, lineno, f.f_globals)
    print 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj)


try:
    print 1/0
except:
    PrintException()

Output:

输出:

EXCEPTION IN (D:/Projects/delme3.py, LINE 15 "print 1/0"): integer division or modulo by zero

回答by acowpy

The simplest way is just to use:

最简单的方法就是使用:

import traceback
try:
    <blah>
except IndexError:
    traceback.print_exc()

or if using logging:

或者如果使用日志记录:

import logging
try:
    <blah>
except IndexError as e:
    logging.exception(e)

回答by Benyamin Jafari

I use the tracebackwhich is simple and robust:

我使用traceback简单而强大的:

import traceback

try:
    raise ValueError()
except:
    print(traceback.format_exc())

Out:

出去:

Traceback (most recent call last):
  File "catch.py", line 4, in <module>
    raise ValueError()
ValueError

回答by grandma

I would suggest using the python logging library, it has two useful methods that might help in this case.

我建议使用 python 日志库,它有两种有用的方法可能在这种情况下有所帮助。

  1. logging.findCaller()

    • findCaller(stack_info=False) - Reports just the line number for the previous caller leading to the exception raised
    • findCaller(stack_info=True) - Reports the line number & stack for the previous caller leading to the exception raised
  2. logging.logException()

    • Reports the line & stack within the try/except block that raised the exception
  1. 日志记录.findCaller()

    • findCaller(stack_info=False) - 仅报告导致引发异常的前一个调用者的行号
    • findCaller(stack_info=True) - 报告导致引发异常的前一个调用者的行号和堆栈
  2. logging.logException()

    • 报告引发异常的 try/except 块中的行和堆栈

For more info checkout the api https://docs.python.org/3/library/logging.html

有关更多信息,查看 api https://docs.python.org/3/library/logging.html