473,655 Members | 3,105 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

AW: traceback as string

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):
self.s += s
def read(self):
return self.s
def catch(self):
traceback.print _exc(None, self)

if __name__ == '__main__':
myTcb = MyTraceback()
try:
a = 1/0
except:
myTcb.clear()
myTcb.catch()
print myTcb.read()
############### ############### ############### ############### ##########

Call clear() each time before you expect a new traceback output. You can
import this class and don't need to import traceback in your main project.
Oliver

"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
--
http://mail.python.org/mailman/listinfo/python-list
Jul 18 '05 #1
1 2039
On Thu, 18 Dec 2003 11:44:46 +0100, "Oliver Walczak" <ol************ @momatec.de> wrote:
This seems to be a quite difficult approach. Try this:

[ snip nice code]
Here is a variant with repeat counting (may be a bit format-sensitive):
I rather wish something like it was built into the traceback print itself,
especially when recursing forever interactively, and one loses initial output context.

############### ############### ############### ############### #########
import traceback

class MyTraceback:
def __init__(self):
self.clear()
def clear(self):
self.line = []
self.lines = []
self.repeat = 0
def write(self, s):
self.line.appen d(s)
if s[-1:] == '\n':
s = ''.join(self.li ne)
self.line = []
self.lines.appe nd(s)
if len(self.lines) >=4 and self.lines[-4:-2] == self.lines[-2:]:
self.repeat += 1
del self.lines[-2:]
else:
if self.repeat and s!= self.lines[-3]:
if self.repeat==1:
self.lines.exte nd(self.lines[-2:])
else:
self.lines.inse rt(-1,
' *** previous two lines repeated %s times ***\n\n'% self.repeat)
self.repeat = 0
def read(self):
return ''.join(self.li nes + self.line)
def catch(self):
traceback.print _exc(None, self)

if __name__ == '__main__':
myTcb = MyTraceback()
def foo(n):
if n<0: foo(n) # blow stack
print '---> foo(%s)'%n
if n>0: foo(n-1)
1/0
try:
foo(5)
except:
myTcb.clear()
myTcb.catch()
print myTcb.read()
try:
foo(-5)
except:
myTcb.clear()
myTcb.catch()
print myTcb.read()
############### ############### ############### ############### ##########

Result:

[13:19] C:\pywk\clp>myt racebk.py
---> foo(5)
---> foo(4)
---> foo(3)
---> foo(2)
---> foo(1)
---> foo(0)
Traceback (most recent call last):
File "C:\pywk\clp\my tracebk.py", line 41, in ?
foo(5)
File "C:\pywk\clp\my tracebk.py", line 38, in foo
if n>0: foo(n-1)
*** previous two lines repeated 4 times ***

File "C:\pywk\clp\my tracebk.py", line 39, in foo
1/0
ZeroDivisionErr or: integer division or modulo by zero

Traceback (most recent call last):
File "C:\pywk\clp\my tracebk.py", line 47, in ?
foo(-5)
File "C:\pywk\clp\my tracebk.py", line 36, in foo
if n<0: foo(n) # blow stack
*** previous two lines repeated 998 times ***

RuntimeError: maximum recursion depth exceeded

Regards,
Bengt Richter
Jul 18 '05 #2

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
3
3880
by: John Hunter | last post by:
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()
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
8296
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8710
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
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
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();...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4299
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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.

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.