Get Only the Last Items in a Traceback

gregpinero at gmail.com gregpinero at gmail.com
Tue Sep 11 22:09:28 EDT 2007


I'm running code via the "exec in context" statement within a much
larger program.  What I would like to do is capture any possible
errors and show a pretty traceback just like the Python interactive
interpreter does, but only show the part of the traceback relating to
the code sent to exec.

For example here is the code I'm using:

try:
    exec code
except Exception,Err:
    traceback.print_exc()

Which gives me something like this when it catches an exception:

Traceback (most recent call last):
  File "/....py", line 843, in run
    semi_safe_exec.safe_eval(code.replace('\r',''),context,5)
  File ".....py", line 400, in safe_eval
    exec_timed(code, context, timeout_secs)
  File ".....py", line 353, in exec_timed
    exec code in context
  File "<string>", line 7, in ?
  File "<string>", line 5, in func2
  File "<string>", line 2, in func1
ZeroDivisionError: integer division or modulo by zero

What I want to print instead is just something like:

Traceback (most recent call last):
  File "<string>", line 7, in ?
  File "<string>", line 5, in func2
  File "<string>", line 2, in func1
ZeroDivisionError: integer division or modulo by zero

Thanks in advance for the help.

-Greg

P.S. if it matters, for this example, code in exec code is:

def func1():
    print 7/0

def func2():
    func1()

func2()




More information about the Python-list mailing list