Tags Python

Update (14.01.2011): A version of this code for Python 3 is available here.

Here's a method to run Python CGI scripts locally, for testing. It employs the BaseHTTPServer and CGIHTTPServer standard modules to run a simple CGI-capable web server on your computer.

Here's the code implementing the server:

import CGIHTTPServer
import BaseHTTPServer

class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
    cgi_directories = ["/cgi"]

PORT = 9999

httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()

This server assumes the directory it was run in is the root directory. It will run CGI scripts from the directory cgi, relative it its root. Place the following simple script in cgi and call it test.py:

#!/usr/bin/env python

print "Content-type: text/html"
print
print "<html><head><title>Situation snapshot</title></head>"
print "<body><pre>"

import sys
sys.stderr = sys.stdout
import os
from cgi import escape

print "<strong>Python %s</strong>" % sys.version

for k in sorted(os.environ.keys()):
    print "%s\t%s" % (escape(k), escape(os.environ[k]))

print "</pre></body></html>"

All this script does it to print out a message and the environment variables. Now, after running the server, visit (in your browser) http://localhost:9999/cgi/test.py and you will hopefully see the expected results.

This method can be used to locally test CGI scripts before uploading them to a real server.