AW: traceback as string

Bengt Richter bokr at oz.net
Thu Dec 18 22:06:02 CET 2003


On Thu, 18 Dec 2003 11:44:46 +0100, "Oliver Walczak" <oliver.walczak at 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




More information about the Python-list mailing list