Running Python CGI Scripts on a Host Server

The first step in web programming with Python is to verify that you can run CGI scripts on your web server. Here is a simple script you can run, the equivalent of Hello, World!:


#!/usr/bin/python

print 'Content-Type: text/html'
print
print '<html>'
print '<head><title>Hello from Python</title></head>'
print '<body>'
print '<h2>Hello from Python</h2>'
print '</body></html>'


The first line must contain the "#!", followed by the full path to reach the system Python interpreter, as it would be typed on a command line.

If you are hosted on a UNIX system, be sure that you upload your file with lines of text terminated in UNIX format rather than in Microsoft Windows format. This is usually handled properly by uploading files in text mode (rather than binary).

Finally, make sure that your uploaded file has execute permission. You can do this by

$ chmod 755 hello.py
where hello.py is the filename.

Then you should be able to run your CGI script by linking to a URL such as

 <a href="http://domain_name/cgi-bin/hello.py">hello</a>

See a working example.


Maintained by John Loomis, last updated 25 January 2008