DebuggingΒΆ

To catch syntax error messages run the script in a local shell before uploading to the server. Header errors are hard to catch unless you have access to the server logs. In case you have, look for error_log and access_log in Linux and for error.log and access.log in Windows.

For a nice exceptions report there is the cgitb module. It will show a traceback inside a context. The default output is sent to standard output as HTML:

#!/usr/bin/env python
print "Content-Type: text/html"
print
import cgitb; cgitb.enable()
print 1/0

The cgitb.handler() function can be used to handle only the catched exceptions:

#!/usr/bin/env python
print "Content-Type: text/html"
print
import cgitb
try:
   f = open('non-existent-file.txt', 'r')
except:
   cgitb.handler()

There is also the option for a crude approach making the header text/plain and setting the standard error to standard out:

#!/usr/bin/env python
print "Content-Type: text/plain"
print
import sys
sys.stderr = sys.stdout
f = open('non-existent-file.txt', 'r')

Will output this:

Traceback (most recent call last):
  File "/var/www/html/teste/cgi-bin/text_error.py", line 6, in ?
    f = open('non-existent-file.txt', 'r')
IOError: [Errno 2] No such file or directory: 'non-existent-file.txt'

Warning

These techniques expose information that can be used by an attacker. Use it only while developing/debugging. Once in production disable them.