Serve.py
Revision as of 12:03, 14 January 2014 by Michael Murtaugh (talk | contribs)
Simple
python -m SimpleHTTPServer
In a time when the terms of "sharing" become increasingly contested and dictated by platforms vying for our personal data and attention, this simple one-liner, which shares the current directory (and potentially sub-directories) on one's local network takes on a political dimension. I share therefore I am!
Python 3 Version (with port)
python -m http.server 8888 &
Server with CGI support
Script to make a local webserver with CGI.
#!/usr/bin/env python
import BaseHTTPServer, CGIHTTPServer, sys, argparse
import cgitb; cgitb.enable() ## This line enables CGI error reporting
parser = argparse.ArgumentParser(description='Happy to serve you')
parser.add_argument('--port', type=int, default=8000, help='the port number to listen to')
args = parser.parse_args()
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", args.port)
handler.cgi_directories = ["/cgi-bin"]
print "Listening on http://localhost:{}".format(args.port)
httpd = server(server_address, handler)
httpd.serve_forever()
Automatic port selection and nicer errors
#!/usr/bin/env python
import BaseHTTPServer, CGIHTTPServer
import cgitb; cgitb.enable() ## This line enables CGI error reporting
import sys, argparse, socket
from time import sleep
parser = argparse.ArgumentParser(description='Happy to serve you')
parser.add_argument('--port', type=int, default=8000, help='the port number to listen to')
parser.add_argument('-t', '--notryports', default=True, action="store_false", help='if a port is busy, automatically try other ones')
parser.add_argument('--share', default=False, action="store_true", help='Run as server accessible via your local network')
args = parser.parse_args()
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", args.port)
handler.cgi_directories = ["/cgi-bin"]
tryports = args.notryports
port = args.port
while True:
try:
server_address = ("", port)
httpd = server(server_address, handler)
print "Serving from --> http://localhost:{}".format(port)
httpd.serve_forever()
except socket.error, e:
if e.errno == 98:
if tryports:
if port < 2000:
port = 2000
else:
port += 1
sleep(.01)
else:
print """
====================================
Error: port ({0}) is already in use
====================================
You can pick another port number
(for example 9999) with:
serve --port 9999
""".format(port)
break
else:
raise(e)