473,503 Members | 2,720 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.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
--
http://mail.python.org/mailman/listinfo/python-list
Jul 18 '05 #1
1 2018
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.append(s)
if s[-1:] == '\n':
s = ''.join(self.line)
self.line = []
self.lines.append(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.extend(self.lines[-2:])
else:
self.lines.insert(-1,
' *** previous two lines repeated %s times ***\n\n'% self.repeat)
self.repeat = 0
def read(self):
return ''.join(self.lines + 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>mytracebk.py
---> foo(5)
---> foo(4)
---> foo(3)
---> foo(2)
---> foo(1)
---> foo(0)
Traceback (most recent call last):
File "C:\pywk\clp\mytracebk.py", line 41, in ?
foo(5)
File "C:\pywk\clp\mytracebk.py", line 38, in foo
if n>0: foo(n-1)
*** previous two lines repeated 4 times ***

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

Traceback (most recent call last):
File "C:\pywk\clp\mytracebk.py", line 47, in ?
foo(-5)
File "C:\pywk\clp\mytracebk.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
4927
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
3870
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...
5
3629
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
1996
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
1981
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
4333
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
1996
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
1668
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
1342
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
7063
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
7313
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...
0
7441
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...
0
5558
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,...
1
4987
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...
0
4663
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...
0
3156
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...
0
3146
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1489
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 ...

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.