Files
q-tools/web/webserver.py
Ville Rantanen dfd5111bea more python3
2020-10-12 11:41:17 +03:00

54 lines
1.5 KiB
Python
Executable File

#!/usr/bin/env python3
import sys, os
import http.server
from http.server import SimpleHTTPRequestHandler
def setup_options():
''' Create command line options '''
from argparse import ArgumentParser
parser=ArgumentParser()
parser.add_argument("-p",type=int,dest="port",default=8000,
help="Server port (Default: %(default)s)")
parser.add_argument("-a",type=str,dest="address",default="",
help="Server bind address. Use localhost for privacy. Defaults to all interfaces.")
parser.add_argument("rootpath",type=str,action="store",default=os.path.abspath('.'),nargs='?',
help="Root path of the server")
options=parser.parse_args()
if not os.path.exists(options.rootpath):
parser.error("Path does not exist")
options.rootpath = os.path.abspath(options.rootpath)
return options
def serve(options):
""" Run the web server """
HandlerClass = SimpleHTTPRequestHandler
ServerClass = http.server.HTTPServer
Protocol = "HTTP/1.0"
server_address = (options.address, options.port)
os.chdir(options.rootpath)
HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print(("Serving http://"+ sa[0]+ ":"+ str(sa[1])+ "/"))
try:
httpd.serve_forever()
except KeyboardInterrupt:
httpd.server_close()
except OSError:
httpd.server_close()
if __name__ == "__main__":
options=setup_options()
serve(options)