Source From Here
Question
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:
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?
How-To
Solution, printing filename, linenumber, line itself and exception descrition:
Execution Result:
Supplement
* Python package - linecache — Random access to text lines
* Python package - traceback — Print or retrieve a stack traceback
Question
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))
How-To
Solution, printing filename, linenumber, line itself and exception descrition:
- import linecache
- import sys
- def PrintException():
- # This function returns a tuple of three values that give information about the exception that is currently being handled.
- # More: https://docs.python.org/2/library/sys.html#sys.exc_info
- exc_type, exc_obj, tb = sys.exc_info()
- f = tb.tb_frame
- # This function returns the current line number set in the traceback object.
- lineno = tb.tb_lineno
- filename = f.f_code.co_filename
- linecache.checkcache(filename)
- line = linecache.getline(filename, lineno, f.f_globals)
- print 'EXCEPTION IN ({0}, LINE {1} "{2}"): {3}'.format(filename, lineno, line.strip(), exc_obj)
- try:
- print 1/0
- except:
- PrintException()
Supplement
* Python package - linecache — Random access to text lines
* Python package - traceback — Print or retrieve a stack traceback
沒有留言:
張貼留言