473,387 Members | 1,420 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

traceback as string


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

Jul 18 '05 #1
3 3866

"John Hunter" <jd******@ace.bsd.uchicago.edu> wrote in message
news:ma*************************************@pytho n.org...

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]))
-------------------------------------------

Colin Brown
PyNZ
Jul 18 '05 #2
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)

================================================== ==
Jul 18 '05 #3
st***@ferg.org (Stephen Ferg) writes:
[...]
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
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: leroybt.rm | last post by:
I don't understand why this does not work: <FILE1> test1.py #Import Packages import string # data=0 data=data+1
1
by: Oliver Walczak | last post by:
This seems to be a quite difficult approach. Try this: ##################################################################### import traceback class MyTraceback: def __init__(self):...
5
by: Bob Greschke | last post by:
I want to cause any traceback output from my applications to show up in one of my dialog boxes, instead of in the command or terminal window (between running on Solaris, Linux, OSX and Windows...
4
by: billiejoex | last post by:
Hi there, I'm facing a case where I need to get the traceback outptut when occurring an exception. I solved such problem by using traceback module in conjunction with StringIO: import...
8
by: gregpinero | last post by:
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...
1
by: Sami Vaisanen | last post by:
Hello group, I'm trying to get the Python exception information (message and traceback) stored into a string in my C++ code. However all i get back is the string "None". All the checks pass and...
1
by: Sami Vaisanen | last post by:
This is becoming utterly painful process.... I found out that the return value from "format_exception" function is NOT a list, i.e. PyList_Check() fails. PySequence_Check() succeeds but then...
21
by: Agustin Villena | last post by:
Hi! is there anyway to show the class of a method in an exception's traceback? For example, the next code class Some(object): def foo(self,x): raise Exception(x)
0
by: Gabriel Genellina | last post by:
En Mon, 26 May 2008 05:31:27 -0300, <Dominique.Holzwarth@ch.delarue.comescribió: Don't inherit from Exception - you should be able to log *any* exception, not only this specific one, I presume?...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.