Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata