Pythonのお手軽webサーバ機能

単純なWebサーバだと実質3行で作れるというお手軽さでした。
スクリプトを実行したディレクトリがDocumentRootになります。

#!/usr/bin/env python

import SimpleHTTPServer
import SocketServer
import sys

def run(port):
    print "listening port is ", port
    
    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    
    httpd = SocketServer.TCPServer(("", port), Handler)
    
    httpd.serve_forever()
    
if __name__ == "__main__":
    port = 8000
    if (len(sys.argv) == 2):
        port = int(sys.argv[1])
    run(port)

実行中はコンソールにログが出ます。

[masami@moonlight:~/public_html]% ../experiment/webserver/server.py 10000
listening port is  10000
localhost - - [25/Apr/2010 23:04:53] "GET /index.html HTTP/1.1" 200 -
localhost - - [25/Apr/2010 23:04:53] code 404, message File not found
localhost - - [25/Apr/2010 23:04:53] "GET /favicon.ico HTTP/1.1" 404 -
localhost - - [25/Apr/2010 23:04:56] code 404, message File not found
localhost - - [25/Apr/2010 23:04:56] "GET /favicon.ico HTTP/1.1" 404 -
localhost - - [25/Apr/2010 23:04:59] code 404, message File not found
localhost - - [25/Apr/2010 23:04:59] "GET /test.htmk HTTP/1.1" 404 -
localhost - - [25/Apr/2010 23:05:01] "GET /test.html HTTP/1.1" 200 -