Python异常处理——行号 [英] Python exception handling - line number

查看:29
本文介绍了Python异常处理——行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.
" % 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?

谢谢.

推荐答案

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

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

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

这篇关于Python异常处理——行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆