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.
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.
Tags: cgi
Another way to catch stderr in a CGI.
Multithreading. Try this in a program that uses threads ;-)
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.