| import http.server | |
| import socketserver | |
| import os | |
| import random | |
| def find_available_port(start=49152, end=65535): | |
| for port in random.sample(range(start, end + 1), end - start + 1): | |
| try: | |
| with socketserver.TCPServer(("0.0.0.0", port), None) as s: | |
| pass | |
| return port | |
| except OSError: | |
| continue | |
| raise RuntimeError("No available port found") | |
| PORT = find_available_port() | |
| DIRECTORY = os.path.dirname(os.path.abspath(__file__)) | |
| class Handler(http.server.SimpleHTTPRequestHandler): | |
| def __init__(self, *args, **kwargs): | |
| super().__init__(*args, directory=DIRECTORY, **kwargs) | |
| def log_message(self, format, *args): | |
| pass | |
| if __name__ == "__main__": | |
| with socketserver.TCPServer(("", PORT), Handler) as httpd: | |
| print(f"Serving at http://localhost:{PORT}") | |
| httpd.serve_forever() | |