0

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.

2
  • 1
    What is the exact error stacktrace ? Commented Nov 19, 2013 at 19:19
  • I'm surprised you get an "internal server error" when running a simple script. I noticed the 'apache' tag but that doesn't say anything about the way you actually run your script... Commented Nov 19, 2013 at 19:26

1 Answer 1

6

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).

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
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, Thanks. I checked, and it says 'malformed header from script. Bad header=hi: test.py'. What does it mean?
That the script's output is not valid for CGI. It should output valid HTTP headers before its regular output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.