1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
#!/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()
|