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

Fast PHP server

Since PHP 4.x, there is a CLI SAPI web server. As a tester you simply go to the folder and start the server.

Example

# change to directory where server should start
$ cd /path/to/folder

# start server with specific port
$ php -S localhost:8100

Now start your browser and insert the URL “localhost:8100”. With “Ctrl+c” you can stop the server.

Extended

# explicit document root
$ cd /path/to/folder
$ php -S localhost:8100 -t foo/bar/

# specific configuration
$ cd /path/to/folder
$ php -S localhost:8100 -c php.ini