traceback as string

J

John Hunter

What is the best way to get the traceback as a string. I tried

def exception_to_str(s = None):

sh = StringIO.StringIO()
if s is not None: print >>sh, s
traceback.print_stack(sh)
return sh.getvalue()


but got

Traceback (most recent call last):
File "/home/jdhunter/seizure/python/eegdb/eegview/eegview.py", line 944, in on_menuFileOpen_activate
msg = exception_to_str('Could not read data:')
File "/hunter/jdhunter/python/projects/jdh/jdh/cbook.py", line 707, in exception_to_str
traceback.print_stack(sh)
File "/usr/local/lib/python2.3/traceback.py", line 235, in print_stack
print_list(extract_stack(f, limit), file)
File "/usr/local/lib/python2.3/traceback.py", line 266, in extract_stack
lineno = f.f_lineno

Thanks!
John Hunter
 
C

Colin Brown

John Hunter said:
What is the best way to get the traceback as a string.

I define the following module "Excepts.py" for logging exceptions in daemon
processes:

------------------------------------------
import sys,traceback

def error():
tb =
traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info(
)[2])
return tb[len(tb)-1].replace('\n','')

def errorstack():
return
''.join(traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.e
xc_info()[2]))
 
S

Stephen Ferg

I haven't been using this function for very long, but it seems to work.

You pass it the exception object, and it returns a string.

===================================================

def exception_format(e):
"""Convert an exception object into a string,
complete with stack trace info, suitable for display.
"""
import traceback
info = "".join(traceback.format_tb(sys.exc_info()[2]))
return str(e) + "\n\n" + info

====================================================

Here's an example of how to use it.

==================================================

try:
main1()
except Exception, e:
print exception_format(e)

====================================================
 
J

John J. Lee

try:
main1()
except Exception, e:
print exception_format(e)
[...]

Just a semi-random warning for anybody as stupid as me: "finally:"
blocks do not handle exceptions, so don't expect things like using the
traceback module to work there:

try:
main1()
finally:
print exception_format(e) # WRONG


I spent a long time tracing through the Python source code trying to
track down a non-existent bug in a C extension, thanks to this
misconception. :-(


John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top