Create a simple CGI server for Python

Sometimes there is a need that python scripts are executed directly from the browser. With CGIHTTPServer it goes very easily.

Create Folders

# create project folder
$ mkdir MyProject

# create cgi-bin folder
$ mkdir MyProject/cgi-bin

Create Python File

# create test.py
$ touch MyProject/cgi-bin/test.py

# modify test.py
$ vim MyProject/cgi-bin/test.py

Add some very simple content like:

#!/usr/bin/env python

print "Content-Type: text/html\n"
print "<html><head><title>Hello world</title></head>"
print "<body>"
print "<h1>hello world...</h1>"
print "<body>\n</html>"

Change the file permission

# change the permission
$ chmod 750 MyProject/cgi-bin/test.py

Run CGIHTTPServer

# change to project folder
$ cd MyProject/

# run CGIHTTPServer
$ python -m CGIHTTPServer

Now open the browser and call URL: “http://localhost:8000/cgi-bin/test.py

Python 3

In Python 3.3, the replacement for python -m CGIHTTPServer is python3 -m http.server --cgi.

Other examples

# show help
$ python3 -m http.server --help

# run server in Python 3
$ python3 -m http.server 8080

# run server in Python 3 on loopback interface
$ python3 -m http.server 8080 --bind 127.0.0.1