Python异常处理 - 行号 [英] Python exception handling - line number
问题描述
很难找出问题发生在代码中的哪个位置。如果我知道错误提出了哪一行,这将有很大的帮助。如果我使用以下代码:
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屋!