CGI Scripts

Patricia Hawkins phawkins at
Sun Mar 5 02:58:55 CET 2000

>>>>> "AME" == Anders M Eriksson <anders.eriksson at> writes:
AME> First I would add two 'debug' lines to the script

AME> sys.stderr = sys.stdout
AME> print "Content-Type: text/plain\n"


AME> One thing I have noticed is that if I get an error/exception in the
AME> script then I get somekind of default blank HTML-page.

Or you could read documentation in and follow the debugging
suggestions contained therein:

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:

        1. Import the traceback module (before entering the
        2. Make sure you finish printing the headers and the blank
           line early
        3. Assign sys.stderr to sys.stdout
        3. Wrap all remaining code in a try-except statement
        4. In the except clause, call traceback.print_exc()

For example:

        import sys
        import traceback
        print "Content-type: text/html"
        sys.stderr = sys.stdout
                ...your code here...
                print "\n\n<PRE>"

Notes: The assignment to sys.stderr is needed because the traceback
prints to sys.stderr.  The print "\n\n<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"
        ...your code here...

This relies on the Python interpreter to print the traceback.  The
content type of the output is set to plain text, which disables all
HTML processing.  If your script works, the raw HTML will be displayed
by your client.  If it raises an exception, most likely after the
first two lines have been printed, a traceback will be displayed.
Because no HTML interpretation is going on, the traceback will

When all else fails, you may want to insert calls to log() to your
program or even to a copy of the file.  Note that this requires
you to set cgi.logfile to the name of a world-writable file before the
first call to log() is made!


Successfully verbose user of speech recognition software.

More information about the Python-list mailing list