Welcome, guest | Sign In | My Account | Store | Cart

The standard library modules SimpleHTTPServer and CGIHTTPServer are extremely useful, but the documentation hides their virtues. I hope to improve the situation with this recipe.

Python, 5 lines
1
2
3
4
5
$ python -m SimpleHTTPServer # requires Python 2.4

or

$ python -c "from SimpleHTTPServer import test; test()" # older Python

If you want to serve files from the current directory, just give the previous command on the shell prompt and open a browser at http://localhost:8000.

If you have a cgi script located in /cgi-bin/myscript.py, you can test it by giving

$ cd $ python -m CGIHTTPServer

and going at http://localhost:8000/myscript.py

Notice that this will work for non-Python CGI scripts too!

The advantage of using CGIHTTPServer is that you will get the logs and the error messages in a shell window and not in a log file. This is of invaluable help during debugging.

You can use a port different from port 8000, just give

$ python -m

2 comments

Paul Moore 19 years, 2 months ago  # | flag

That last bit should have been

python -m SimpleHTTPServer PORTNO
axis z 18 years, 12 months ago  # | flag

why os.environ can not be passed to child ? A python CGI program can run on linux but not on windows. By looking at CGIHTTPServer.py, we found out the reason: on windows, the parent cannot pass os.environ to child demonstrated as below:

main.py

import os, sys, shutil

env = {}

env["AAA"] = "111"
os.environ.update(env)
print os.environ["AAA"] # ok, updated successful

files = os.popen3(sys.argv[1], "b")

fi, fo, fe = files[0], files[1], files[2]

shutil.copyfileobj(fo, sys.stdout)

errors = fe.read()

fe.close()

if errors: print errors

sts = fo.close()

if sts:

   print "exit %#x" % sts

else:

   print "exit ok"


test.py

import os, sys

if os.environ.has_key["AAA"]:

   print "ok, got AAA"

else:

   print "failure"

c:\www\cgi-bin>main.py test.py

it will print failure

main.py is adopted from CGIHTTPServer.py ?!

Created by Michele Simionato on Wed, 2 Feb 2005 (PSF)
Python recipes (4591)
Michele Simionato's recipes (12)

Required Modules

  • (none specified)

Other Information and Tasks