#!/usr/bin/env python3 from argparse import ArgumentParser from collections.abc import Sequence from typing import Optional from pathlib import Path from os import PathLike, fspath from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from functools import partial def serve(bind: str, port: int, directory: PathLike): handler = partial(SimpleHTTPRequestHandler, directory=fspath(directory)) with ThreadingHTTPServer((bind, port), handler) as httpd: print(*httpd.socket.getsockname()) try: httpd.serve_forever() except KeyboardInterrupt: return def main(argv: Optional[Sequence[str]] = None) -> None: parser = ArgumentParser() parser.add_argument( "-b", "--bind", metavar="ADDRESS", default="", help="bind to this address" ) parser.add_argument( "-p", "--port", default=8080, type=int, help="bind to this port" ) parser.add_argument( "directory", type=Path, default=Path.cwd(), nargs="?", help="serve this directory", ) args = parser.parse_args(argv) try: serve(**vars(args)) except KeyboardInterrupt: pass if __name__ == "__main__": main()