debugging CGI scripts
Sam Penrose
see at message.body
Tue Aug 22 00:23:22 EDT 2000
1) cgi.py has a built-in traceback exception function. I think it's
called print_traceback_exec, but a quick read of the source should tell
you. You can also redirect sys.stderr to sys.stdout, along the lines of
Adam's suggestion.
2) I have my own little function which prints a variable of choice.
def bail(message):
"""Print message to browser window and call sys.exit()"""
import sys
print BASIC_HEADER #'Content type: text/html\n'
if type(message) is type({}):
for k, v in message.items(): print k, ': ', v
else: print message
sys.exit()
You can certainly embellish it further. My top level flow-control
then reads:
try:
main()
except SystemError: pass #calling bail()
except: cgi.print_traceback_exec() #or whatever it's called.
3) I find after doing this for a year the errors fall into certain
predictable types; string substitution mismatches being the most common
(and thoroughly frustrating until you get a feel for them). I used to
lose about a half a day a week to one or two absolutely baffling errors.
Now I'm rarely stuck for more than a couple minutes. Usually dropping
bail(suspiciousVariable) into the code, saving, and reloading makes the
problem immediately evident.
In article <39a0ab79$1_2 at news.nwlink.com>, "Adam Vandenberg"
<adamv at nwlink.com> wrote:
> lynx <a at b.c> wrote in message
> news:pJ%n5.43052$QD5.426611 at news.corecomm.net...
> > any good, simple work-even-remotely-alike for perl's CGI::Carp out
> > there,
>
> Here is something I use for debugging Python CGI scripts.
> It's based on various other similar debugging scripts I found and glommed
> together.
> --- debug.py ---
> #!/usr/bin/python
> import os, sys, string
> import cgi
>
> filename = os.environ["PATH_TRANSLATED"]
>
> # Grab the real stdout from the script we are trying to debug
> import StringIO
> real_stdout = sys.stdout
> sys.stdout = StringIO.StringIO()
>
> try:
> execfile(filename)
> real_stdout.write( sys.stdout.getvalue() )
> except:
> real_stdout.write ("Content-type: text/html\n\n")
>
> real_stdout.write ("debugging: " + filename + "<br><br>")
>
> import traceback
>
> IOBuffer = StringIO.StringIO()
> traceback.print_exc(file=IOBuffer)
>
> HTML = IOBuffer.getvalue()
> HTML = string.replace(HTML,"&","amp;")
> HTML = string.replace(HTML,"<","<")
> HTML = string.replace(HTML,">",">")
> HTML = string.replace(HTML,"\n","<br>")
> HTML = string.replace(HTML,"\t"," ")
>
> real_stdout.write("<tt>")
> real_stdout.write(HTML)
> real_stdout.write("</tt>")
>
> sys.exit(0)
>
>
> I place this in my web's root folder and include it in the path.
> Debug, send tracebacks to browser: http://adamv.com/debug.py/toy/test.py
>
> Hope this helps,
> Adam Vandenberg, Pythoneer 3rd class.
--
spenrose at well dot com
More information about the Python-list
mailing list