Commits

ikame committed d80735e

Command for running a simple http server

Comments (0)

Files changed (1)

+#!/usr/bin/env python
+"""Run a web server in the specified directory."""
+
+import sys
+import os
+import socket
+import re
+import argparse
+import multiprocessing
+from BaseHTTPServer import HTTPServer
+from CGIHTTPServer import CGIHTTPRequestHandler
+
+
+_VALID_ADDRESS = r'[a-z0-9\.]*:(\d{4}|\d{2})'
+
+
+def run_server(address):
+    try:
+        httpd = HTTPServer(address, CGIHTTPRequestHandler)
+    except socket.error, e:
+        print e
+    else:
+        while True:
+            try:
+                httpd.handle_request()
+            except KeyboardInterrupt:
+                break
+    print 'Exiting server process...'
+
+
+def valid_address(value):
+    if re.match(_VALID_ADDRESS, value):
+        host, port = value.split(':')
+        port = int(port)
+    else:
+        raise argparse.ArgumentError
+    return host, port
+
+
+def valid_directory(value):
+    if os.path.isdir(value):
+        value = os.path.abspath(value)
+    else:
+        raise argparse.ArgumentError
+    return value
+
+
+def main(argv=None):
+    if argv is None:
+        argv = sys.argv[1:]
+
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument('-a', '--address', type=valid_address, default=('', 8080),
+                        help=('Address using host:port format or just :port. '
+                              'Default to :8080'))
+    parser.add_argument('directory', type=valid_directory, default=os.getcwd(),
+                        nargs='?',
+                        help=('Root directory. Default to current working '
+                              'directory'))
+    args = parser.parse_args(argv)
+
+    address = args.address
+    os.chdir(args.directory)
+
+    p = multiprocessing.Process(target=run_server, args=(address,))
+    p.start()
+    print 'Spawned server process...'
+    print 'Listening at {0}:{1}...'.format(*address)
+    try:
+        p.join()
+    except KeyboardInterrupt:
+        print 'Exiting parent process...'
+
+
+if __name__ == '__main__':
+    main()