Re: Traceback strings

Guido.van.Rossum@cwi.nl
Sat, 17 Sep 1994 10:44:44 +0200

> I have embedded python into a Gui application and I want to be able to
> show exception strings similar to what the interpreter displays, but I
> want to show them in a window. Has anyone written code similar to
> print_error() that returns a traceback string instead of printing directly
> to a file?

Yes. Since it's not in the 1.0.3 release I'll post it here. This
module is called traceback.py. Hope you don't need documentation at
this stage :-)

======================================================================
# Format and print Python stack traces

import linecache
import string
import sys

def print_tb(tb, limit = None):
if limit is None:
if hasattr(sys, 'tracebacklimit'):
limit = sys.tracebacklimit
n = 0
while tb is not None and (limit is None or n < limit):
f = tb.tb_frame
lineno = tb.tb_lineno
co = f.f_code
filename = co.co_filename
name = co.co_name
print ' File "%s", line %d, in %s' % (filename, lineno, name)
line = linecache.getline(filename, lineno)
if line: print ' ' + string.strip(line)
tb = tb.tb_next
n = n+1

def extract_tb(tb, limit = None):
if limit is None:
if hasattr(sys, 'tracebacklimit'):
limit = sys.tracebacklimit
list = []
n = 0
while tb is not None and (limit is None or n < limit):
f = tb.tb_frame
lineno = tb.tb_lineno
co = f.f_code
filename = co.co_filename
name = co.co_name
line = linecache.getline(filename, lineno)
if line: line = string.strip(line)
else: line = None
list.append(filename, lineno, name, line)
tb = tb.tb_next
n = n+1
return list

def print_exception(type, value, tb, limit = None):
if tb:
print 'Traceback (innermost last):'
print_tb(tb, limit)
if value is None:
print type
else:
if type is SyntaxError:
try:
msg, (filename, lineno, offset, line) = value
except:
pass
else:
if not filename: filename = "<string>"
print ' File "%s", line %d' % (filename, lineno)
i = 0
while i < len(line) and line[i] in string.whitespace:
i = i+1
s = ' '
print s + string.strip(line)
for c in line[i:offset-1]:
if c in string.whitespace:
s = s + c
else:
s = s + ' '
print s + '^'
value = msg
print '%s: %s' % (type, value)

def print_exc(limit = None):
print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback,
limit)

def print_last(limit = None):
print_exception(sys.last_type, sys.last_value, sys.last_traceback,
limit)
======================================================================

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>