473,656 Members | 2,983 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

traceback as string


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

def exception_to_st r(s = None):

sh = StringIO.String IO()
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_st r('Could not read data:')
File "/hunter/jdhunter/python/projects/jdh/jdh/cbook.py", line 707, in exception_to_st r
traceback.print _stack(sh)
File "/usr/local/lib/python2.3/traceback.py", line 235, in print_stack
print_list(extr act_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 3880

"John Hunter" <jd******@ace.b sd.uchicago.edu > wrote in message
news:ma******** *************** **************@ python.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.forma t_exception(sys .exc_info()[0],sys.exc_info()[1],sys.exc_info(
)[2])
return tb[len(tb)-1].replace('\n',' ')

def errorstack():
return
''.join(traceba ck.format_excep tion(sys.exc_in fo()[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_forma t(e):
"""Convert an exception object into a string,
complete with stack trace info, suitable for display.
"""
import traceback
info = "".join(traceba ck.format_tb(sy s.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_forma t(e)

=============== =============== =============== =======
Jul 18 '05 #3
st***@ferg.org (Stephen Ferg) writes:
[...]
try:
main1()
except Exception, e:
print exception_forma t(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_forma t(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
4954
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
2039
by: Oliver Walczak | last post by:
This seems to be a quite difficult approach. Try this: ##################################################################### import traceback class MyTraceback: def __init__(self): self.clear() def clear(self): self.s = '' def write(self, s):
5
3656
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 systems there might not be any command window or terminal window to show the traceback messages in). Do I want to do something like override the print_exc (or format_exc?) method of traceback to get the text of the message and call my dialog box...
4
2003
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 StringIO, traceback try: raise Exception except:
8
1995
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 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
1
4340
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 all pointers get a value from the python API calls. I've also tried with a different function such as PyObject_CallFunctionObjArgs but the result is the same. Thanks
1
2009
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 PySequence_List() gives me back -1. So wtf? I must say the API is crap on this part. Im trying to get error information regarding previous error and if all i get back is another error indicator, then what am I supposed to do? Recursive error...
21
1685
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
1352
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? print_exc writes "the exception currently being handled", not the one you're creating right now. Put the code above into your exception handler: try: 1/0 except: f = open('filename.txt', 'a') traceback.print_exc(file=f)
0
8380
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8598
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7310
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5627
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2721
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1928
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1598
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.