Internal Server Error with very simple python script
Question: I'm new to python, and i'm trying to run a simple script (On a Mac if that's
important).

Now, this code, gives me Internal Server Error:

    
    
    #!/usr/bin/python
    
    print 'hi'
    

But this one works like a charm (Only extra 'print' command):

    
    
    #!/usr/bin/python
    print
    
    print 'hi'
    

Any explanation? Thanks!

Update:

When I run this script from the Terminal everything is fine. But when I run it
from the browser:

    
    
    http://localhost/cgi-bin/test.py
    

I get this error (And again, only if i'm not adding the extra print command).
I use Apache server of course.


Answer: ~~Looks like you're running your script as a CGI-script~~ (your edit confirms
that you're using CGI)

...and the initial (empty) `print` is required to signify the end of the
headers.

Check your Apache's error log (`/var/log/apache2/error.log` probably) to see
if it says '_Premature end of script headers_ ' ([more info
here](http://httpd.apache.org/docs/2.2/howto/cgi.html#troubleshoot)).

**EDIT** : a bit more explanation:

A CGI script in Apache is responsible for generating it's own HTTP response.

An HTTP response consists of a header block, _an empty line_ , and the so-
called _body_ contents. Even though you should generate _some_ headers, it's
not mandatory to do so. However, you do need to output the empty line; Apache
expects it to be there, and if it's not (or if you only output a body which
can't be parsed as headers), Apache will generate an error.

That's why your first version didn't work, but your second did: adding the
empty `print` added the required empty line that Apache was expecting.

This will also work:

    
    
    #!/usr/bin/env python
    
    print "Content-Type: text/html"  # header block
    print "Vary: *"                  # also part of the header block
    print "X-Test: hello world"      # this too is a header, but a made-up one
    print                            # empty line
    print "hi"                       # body
    

