Welcome, guest | Sign In | My Account | Store | Cart

For CGI programmers it's important to display tracebacks in the HTML pages to debug their scripts, but the usual functions in the modules cgi and traceback print to sys.sterr. So this small programm returns the traceback as a string an can even add entities for HTML.

Python, 31 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def ErrorMsg(escape=0):
    """
    returns: string
    
    simualtes the traceback output and if argemument
    <escape> set to 1 (true) the string will be
    converted to fit into html documents without problems.    
    """
    import traceback, sys, string
    
    type=None
    value=None
    tb=None
    limit=None
    type, value, tb = sys.exc_info()
    body = "Traceback (innermost last):\n"
    list = traceback.format_tb(tb, limit) +            traceback.format_exception_only(type, value)
    body = body + "%-20s %s" % (
        string.join(list[:-1], ""),
        list[-1],
        )
    if escape:
        import cgi
        body = cgi.escape(body)
    return body

if __name__=="__main__":
    try:
        1/0
    except:
        print ErrorMsg()
 

Good CGI programms write their output at first into something like StringIO() and then go to write it out. Therefore this function may be helpfull.

3 comments

Noah Spurrier 21 years, 8 months ago  # | flag

Another way to catch stderr in a CGI.

# This redirects errors to the web browser.
# Normally stderr goes to the web server errors log, but
# this will cause the message to go to the user's browser.
import sys
sys.stderr = sys.stdout


# Another thing I do is wrap my entire script in a try block:
# It's also good to wrap your import statements, because sometimes
# these will cause errors. This is my minimal cgi template.
try:
        import traceback, sys, os, cgi
        sys.stderr = sys.stdout
        do_my_cgi_stuff ()
except Exception, e:
        print 'Content-type: text/html\n'
        print
        print '&lt;html&gt;&lt;head&gt;&lt;title&gt;'
        print str(e)
        print '&lt;/title&gt;'
        print '&lt;meta name=&quot;ROBOTS&quot; content=&quot;NOINDEX, NOFOLLOW&quot;&gt;'
        print '&lt;/head&gt;&lt;body&gt;'
        print '&lt;h1&gt;TRACEBACK&lt;/h1&gt;'
        print '&lt;pre&gt;'
        traceback.print_exc()
        print '&lt;/pre&gt;'
        print '&lt;/body&gt;&lt;/html&gt;'
Dirk Holtwick 21 years, 4 months ago  # | flag

Multithreading. Try this in a program that uses threads ;-)

Thomas Guettler 19 years, 5 months ago  # | flag

Since Python2.2 there is cgitb. The cgitb module provides a special exception handler for Python scripts. It displays more than the usual ascii traceback.

It includes the sourcecode of the 3 lines above and below the lines and the values of the variables. This means you should only use it for developement and display a different message in production.