Wrapping Tracebacks in HTML
Credit: Dirk Holtwick
Problem
In a CGI (or other web-based) program,
you want to display tracebacks in the resulting HTML pages (not on
sys.stderr, where tracebacks normally go), using
HTML-compatible markup.
Solution
The
format_tb
and format_exception functions from the
traceback module give us traceback information in
string form, so we can return it to our caller, optionally escaped so
it is printable within an HTML document:
def ErrorMsg(escape=1):
"""
returns: string
simulates a traceback output, and, if argument escape is set to 1 (true),
the string is converted to fit into HTML documents without problems.
"""
import traceback, sys, string
limit = None
type, value, tb = sys.exc_info( )
list = traceback.format_tb(tb, limit
) + traceback.format_exception_only(type, value)
body = "Traceback (innermost last):\n" + "%-20s %s" % (
string.join(list[:-1], ""), list[-1] )
if escape:
import cgi
body = '\n<PRE>'+cgi.escape(body)+'</PRE>\n'
return body
if _ _name_ _=="_ _main_ _":
try:
1/0
except:
print ErrorMsg( )Discussion
Well-structured CGI
scripts and other web programs first write their output into
something like a StringIO instance and then write
it out. Therefore, this recipe may be helpful, as it returns error
information as a multiline string that you can add to the appropriate
StringIO instance in such cases. Normally, you
would want some HTML markup to ensure that the error information is
correctly displayed, and, by default, the ErrorMsg function ...