Hello World

This is the classical “Hello World” in python CGI fashion:

#!/usr/bin/env python
print "Content-Type: text/html"
print
print """\
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
"""

To test your setup save it with the .py extension, upload it to your server as text and make it executable before trying to run it.

The first line of a python CGI script sets the path where the python interpreter will be found in the server. Ask your provider what is the correct one. If it is wrong the script will fail. Some examples:

#!/usr/bin/python
#!/usr/bin/python2.3
#!/usr/bin/python2.4
#!c:\Python24\python.exe
#!c:\Python25\python.exe

The first 3 lines above are Linux paths and the last 2 are Windows paths.

It is necessary that the script outputs the HTTP header. The HTTP header consists of one or more messages followed by a blank line. If the output of the script is to be interpreted as HTML then the content type will be text/html. The blank line signals the end of the header and is required:

print "Content-Type: text/html"
print

Many times the blank line will be written as \n:

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

If you change the content type to text/plain the browser will not interpret the script’s output as HTML but as pure text and you will only see the HTML source. Try it now to never forget. A page refresh may be necessary for it to work.

Client versus Server

When programming for the Web you are in a client-server environment. All python code will be executed at the server only. The client’s http agent (e.g. the browser) will never see a single line of python. In instead it will only get the python script output, be it text, html, css, javascript etc. So do not make things like trying to open a file in the client’s computer as if the python script were running there. You can only achieve what your python script output can and the http clients in general have a very restrictive security context.