eval errors tracing

Tigra tigra_564 at mail.ru
Tue Aug 21 13:34:10 EDT 2001


Hi

Does anyone know how to print SyntaxError traceback for an 'eval'ed
statement. Considering the following code:
=cut
#!/usr/bin/env python

import sys, traceback, exceptions

dict = '''
{
    'a': 'b',
    'c': ,  # This must fail at eval's compile time
    'e': 3/0,
}
'''

try:
    a = eval(dict)
except SyntaxError:
    (exc_type, exc_value, exc_tb) = sys.exc_info()
    print exc_type, exc_value, exc_tb, exc_tb.tb_lineno
=cut

This prints:
=cut
exceptions.SyntaxError invalid syntax (line 4) <traceback object at
0x810d1d8> 15
=cut

So the value of exc_value shows the actual error, while traceback
object describes what happened at line 15 of the test code (where
'eval' is called).
exc_tb.tb_next gives None (not the traceback of the string
compilation).

How can I catch the SyntaxError exception and get the real line number
from it?

Regards,
Sergey



More information about the Python-list mailing list