Next: Common problems and solutions Prev: Testing your CGI script Up: cgi Top: Top
cgi.py
) as a CGI script. When invoked as a script, the file
will dump its environment and the contents of the form in HTML form.
Give it the right mode etc, and send it a request. If it's installed
in the standard cgi-bin
directory, it should be possible to send it a
request by entering a URL into your browser of the form:
http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home
cgi.py
script has been
installed correctly. If you follow the same procedure for your own
script, you should now be able to debug it.
The next step could be to call the cgi
module's test() function from
your script: replace its main code with the single statement
cgi.test()
cgi.py
file itself.
When an ordinary Python script raises an unhandled exception (e.g. because of a typo in a module name, a file that can't be opened, etc.), the Python interpreter prints a nice traceback and exits. While the Python interpreter will still do this when your CGI script raises an exception, most likely the traceback will end up in one of the HTTP server's log file, or be discarded altogether.
Fortunately, once you have managed to get your script to execute
*some* code, it is easy to catch exceptions and cause a traceback to
be printed. The test()
function below in this module is an example.
Here are the rules:
sys.stderr
to sys.stdout
traceback.print_exc()
import sys
import traceback
print "Content-type: text/html"
print
sys.stderr = sys.stdout
try:
...your code here...
except:
print "\n\n<PRE>"
traceback.print_exc()
sys.stderr
is needed because the traceback
prints to sys.stderr
. The print "nn<PRE>"
statement is necessary to
disable the word wrapping in HTML.
If you suspect that there may be a problem in importing the traceback module, you can use an even more robust approach (which only uses built-in modules):
import sys
sys.stderr = sys.stdout
print "Content-type: text/plain"
print
...your code here...