[Tutor] CGI File Woes

Martin Walsh mwalsh at groktech.org
Mon Oct 1 02:44:35 CEST 2007

wormwood_3 wrote:
> Those examples were a lot of help Martin. Turned out the only issue was that I did not have this line right:
> print "Content-type: text/html\n\n"


Glad the examples helped. I should probably fess up and point out that I
mistakenly added an additional newline to that print statement. You only
need one, as the print itself will append an extra. So by adding the
addition \n, a blank line will be sent to the browser as part of the
page content, which shouldn't be a problem for text/html content-types.
But as soon as you want to serve up another content-type (eg. image/png)
you may run into odd problems.

So, the corrected print statement should look like this:

print "Content-type: text/html\n"

or as described in the docs, http://docs.python.org/lib/cgi-intro.html

print "Content-type: text/html"


> With that form, it loaded just fine. It had been running fine from the terminal, but without this line being right, Apache did not know what to do with it.
> I had spoken with my web-hosting provider, but since I had a shared account I was unable to view the server logs. And the person helping me knew nothing about Python (he kept slipping and calling it PHP actually, to my dismay and chagrin:-) ).
> Thanks for all the help, Alan and Martin.
> -Sam
> _________________
> ----- Original Message ----
> From: Martin Walsh <mwalsh at groktech.org>
> To: tutor at python.org
> Sent: Sunday, September 30, 2007 1:07:02 PM
> Subject: Re: [Tutor] CGI File Woes
> No doubt cgitb is a great tool for debugging cgi, but IIUC there are at
> least two instances when you will not get the pretty printed tracebacks
> in the browser when using cgitb. One is after, what I would call, a
> 'compile time' exception such as SyntaxError, in your python code. The
> other is when the python code runs without exception, but you have not
> separated the header and the document content with a newline. At least,
> I have found these to be true when using apache-cgi.
> Consider the following examples:
> #!/usr/bin/env python
> # raises a SyntaxError
> import cgi
> import cgitb; cgitb.enable()
> print "Content-type: text/html\n\n"
> # NOTE: purposeful misspelling of the print statement
> prin "<html><body><p>Hello, world!</p></body></html>"
> # the code above will produce a server 500, with apache
> # complaining about "premature end of script headers"

More information about the Tutor mailing list