Python异常处理 - 行号

JeC*_*eCh 48 python indexing exception

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

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

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

不幸的是,这只能告诉我存在索引错误.我想知道有关异常的更多细节(代码行,变量等),以了解发生了什么.可能吗?

谢谢.

Apo*_*tus 72

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

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()
Run Code Online (Sandbox Code Playgroud)

输出:

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

  • 对于我的 python 3.6.5,我需要使用 print 在最后一行添加括号: print('EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip() , exc_obj)) (4认同)

roo*_*oot 23

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

import sys    
try:
    [][2]
except IndexError:
    print 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno)
Run Code Online (Sandbox Code Playgroud)

印刷品:

Error on line 3
Run Code Online (Sandbox Code Playgroud)

traceback模块文档中的示例:

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
Run Code Online (Sandbox Code Playgroud)


Ben*_*ari 16

我使用traceback简单而强大的:

import traceback

try:
    raise ValueError()
except:
    print(traceback.format_exc())
Run Code Online (Sandbox Code Playgroud)

出去:

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

  • 这是最好的答案。当错误位于函数内部时,其他人无法正确显示错误行 (2认同)

aco*_*wpy 8

最简单的方法就是使用:

import traceback
try:
    <blah>
except IndexError:
    traceback.print_exc()
Run Code Online (Sandbox Code Playgroud)

或者如果使用日志:

import logging
try:
    <blah>
except IndexError as e:
    logging.exception(e)
Run Code Online (Sandbox Code Playgroud)


reu*_*ano 5

为您提供调用堆栈中最后一项的文件、行号和异常

from sys import exc_info
from traceback import format_exception


def print_exception():
    etype, value, tb = exc_info()
    info, error = format_exception(etype, value, tb)[-2:]
    print(f'Exception in:\n{info}\n{error}')

try:
    1 / 0
except:
    print_exception()
Run Code Online (Sandbox Code Playgroud)

印刷

Exception in:
   File "file.py", line 12, in <module>
    1 / 0

ZeroDivisionError: division by zero

Run Code Online (Sandbox Code Playgroud)