ActiveState Code

Recipe 365606: How to serve files from a directory (and/or testing CGI scripts)


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
1
2
3
4
5
$ python -m SimpleHTTPServer # requires Python 2.4

or

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

Discussion

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

Comments

  1. 1. At 3:14 a.m. on 3 feb 2005, Paul Moore said:

    That last bit should have been

    python -m SimpleHTTPServer PORTNO
    
  2. 2. At 6:26 p.m. on 26 apr 2005, axis z said:

    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 ?!

Sign in to comment