can error messages be improved or can they be overridden ?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Feb 23 19:11:54 EST 2009


En Mon, 23 Feb 2009 15:54:03 -0200, <rdmurray at bitdance.com> escribió:
> Stef Mientki <stef.mientki at gmail.com> wrote:

>> but I was looking for a more general solution,
>> in which I don't change the program itself,
>> and where the error messages (in general) become more informative than
>> it is by default.
> No you are not the only one who wishes the error messages were
> more informative.  In one complex application I had, I made my life
> easier with a hack I copied from Zope.  Briefly, at the top level
> of the program I trap all exceptions, get the traceback object from
> sys.exc_info, format it with format_tb, and then process it to add info.
> I applied several enhancements, but the one relevant to you was to grab
> the locals dictionary from the last frame of the traceback, and use a
> regex to split the last source line in the formatted traceback up into
> candidate variable names.  Then I printed the name and the repr of the
> value of any of those names I found in the locals dict.

Have you seen the cgitb module? Despite its name, it's a general purpose  
module.

<http://docs.python.org/library/cgitb.html>

<code>
import cgitb
cgitb.enable(format="txt")

def f(some_list, x, y):
   return some_list[x + y]

def g(a):
   return f(a, 1, 2) - f(a, 3, 4)

g([1,2,3,4])

</code>

Output:
<type 'exceptions.IndexError'>
Python 2.6: c:\apps\python26\python.exe
Mon Feb 23 22:06:22 2009

A problem occurred in a Python script.  Here is the sequence of function  
calls leading up to the error, in the order they occurred.

  C:\TEMP\test_cgitb.py in <module>()
     8   return f(a, 1, 2) - f(a, 3, 4)
     9
    10 g([1,2,3,4])
    11
    12
g = <function g at 0x00B9FB70>

  C:\TEMP\test_cgitb.py in g(a=[1, 2, 3, 4])
     6
     7 def g(a):
     8   return f(a, 1, 2) - f(a, 3, 4)
     9
    10 g([1,2,3,4])
global f = <function f at 0x00B9FB30>
a = [1, 2, 3, 4]

  C:\TEMP\test_cgitb.py in f(some_list=[1, 2, 3, 4], x=3, y=4
)
     3
     4 def f(some_list, x, y):
     5   return some_list[x + y]
     6
     7 def g(a):
some_list = [1, 2, 3, 4]
x = 3
y = 4
<type 'exceptions.IndexError'>: list index out of range
     __class__ = <type 'exceptions.IndexError'>
     [..]
     args = ('list index out of range',)
     message = 'list index out of range'

The above is a description of an error in a Python program. Here is the  
original traceback:

Traceback (most recent call last):
   File "test_cgitb.py", line 10, in <module>
     g([1,2,3,4])
   File "test_cgitb.py", line 8, in g
     return f(a, 1, 2) - f(a, 3, 4)
   File "test_cgitb.py", line 5, in f
     return some_list[x + y]
IndexError: list index out of range


-- 
Gabriel Genellina




More information about the Python-list mailing list