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

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

问题描述

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



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

  try:
result = evaluateData(data)
除了异常,err :
print(Error:%s.\\\
%str(err))

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



谢谢。

解决方案

解决方案,打印文件名,线数,行本身和异常消耗:

  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()

输出:

 code> EXCEPTION IN(D:/Projects/delme3.py,LINE 15print 1/0):整数除或模数为零


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.\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.

解决方案

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

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

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