2013-01-25 122 views
31

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

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

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

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

谢谢。

+1

见http://stackoverflow.com/questions/3702675 /打印的全向扫描功能于蟒蛇,没有休止-的程序! –

+0

https://docs.python.org/2/library/traceback.html#traceback-examples – osa

+2

@JeCh答案看起来不错。请接受一个。要接受它,请单击答案旁边的空白复选标记。 –

回答

16

要简单地得到行号,您可以使用sys,如果您想要更多,请尝试traceback模块。

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

打印

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 
50

解,印刷文件名,行号,行本身和异常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() 

输出:

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

最简单的方法是只使用:

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

,或者使用记录:

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