程式扎記: [ Python 常見問題 ] Python exception handling - line number

標籤

2016年8月31日 星期三

[ Python 常見問題 ] Python exception handling - line number

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:
  1. try:  
  2.     result = evaluateData(data)  
  3. except Exception, err:  
  4.     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?

How-To
Solution, printing filename, linenumber, line itself and exception descrition:
  1. import linecache  
  2. import sys  
  3.   
  4. def PrintException():  
  5.     # This function returns a tuple of three values that give information about the exception that is currently being handled.   
  6.     # More: https://docs.python.org/2/library/sys.html#sys.exc_info  
  7.     exc_type, exc_obj, tb = sys.exc_info()  
  8.     f = tb.tb_frame  
  9.     # This function returns the current line number set in the traceback object.  
  10.     lineno = tb.tb_lineno  
  11.     filename = f.f_code.co_filename  
  12.     linecache.checkcache(filename)  
  13.     line = linecache.getline(filename, lineno, f.f_globals)  
  14.     print 'EXCEPTION IN ({0}, LINE {1} "{2}"): {3}'.format(filename, lineno, line.strip(), exc_obj)  
  15.   
  16.   
  17. try:  
  18.     print 1/0  
  19. except:  
  20.     PrintException()  
Execution Result:
EXCEPTION IN (a.py, LINE 15 "print 1/0"): integer division or modulo by zero

Supplement
Python package - linecache — Random access to text lines
The linecache module allows one to get any line from any file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file. This is used by the traceback module to retrieve source lines for inclusion in the formatted traceback.

Python package - traceback — Print or retrieve a stack traceback
This module provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a “wrapper” around the interpreter.


沒有留言:

張貼留言

網誌存檔