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
$ touch MyProject/cgi-bin/

# modify
$ vim MyProject/cgi-bin/

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/


# change to project folder
$ cd MyProject/

# run CGIHTTPServer
$ python -m CGIHTTPServer

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

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