This is just a blog to try and spread some of the knowledge that has been freely given to me by the wider community, without which I'd get absolutely nothing accomplished. I hope this benefits some of you out there.

Tuesday, June 9, 2009

Python Simple HTTP Server



Recently I have gotten into using python for as many things as I can. So far the results have been good; I like the significant white space, and most functions are fairly intuitive.

Python also makes nearly a program as short as possible. Starting in version 2.5 there is a very easy way to start a http server for testing and sharing a file with a friend. I've cobbled together a few examples that get progressively more involved. I take no credit for writing these commands/scripts.

python -m SimpleHTTPServer 9914 

OR
python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"

And finally:

#!/usr/bin/python

import BaseHTTPServer, SimpleHTTPServer

import os
import sys

def run(server_class=BaseHTTPServer.HTTPServer,
handler_class=SimpleHTTPServer.SimpleHTTPRequestHandler):
print 'Server version:',handler_class.server_version

port=8000

if len(sys.argv)>1:
if sys.argv[1].isdigit():
port=int(sys.argv[1])
server_address = ('', port)

httpd = server_class(server_address, handler_class)

myurl='http://localhost:'+str(server_address[1])+'/'
print 'Your Server is running on:',myurl
print 'and serving files from:',os.getcwd(),'and below.'
print 'To stop the server, type ^C.'

if 'b' in sys.argv:
print 'Trying to start webbrowser...'
import webbrowser
webbrowser.open(myurl)

httpd.serve_forever()

run()

No comments:

Post a Comment

Followers