-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart_server.py
More file actions
executable file
·57 lines (43 loc) · 1.59 KB
/
start_server.py
File metadata and controls
executable file
·57 lines (43 loc) · 1.59 KB
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
48
49
50
51
52
53
54
55
56
57
"""
Script to start the HTTP server and open it in a web browser.
"""
import os
import signal
import socket
import subprocess
import webbrowser
def find_open_port(min_port: int = 8000, max_port: int = 9000) -> int:
"""Find an open port in port range, fallback to system-assigned if needed."""
# By default, only bind server to localhost IP
ip_address = os.getenv("BIND_IP", "127.0.0.1")
for port in range(min_port, max_port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind((ip_address, port))
return port
except OSError:
continue
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((ip_address, 0))
return s.getsockname()[1]
def main():
"""Start the HTTP server and open it in a web browser."""
port = find_open_port()
print(f"Starting server on port {port}...")
with subprocess.Popen(
["python3", "-m", "http.server", str(port)], start_new_session=True
) as process:
try:
webbrowser.open(f"http://localhost:{port}")
process.wait()
except KeyboardInterrupt:
print("\nTerminating the server...")
os.killpg(os.getpgid(process.pid), signal.SIGTERM)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
print("Server didn't terminate gracefully, forcing shutdown...")
os.killpg(os.getpgid(process.pid), signal.SIGKILL)
print("Server stopped.")
if __name__ == "__main__":
main()