2024-01-25 16:07:27 +00:00
|
|
|
import os
|
2024-01-25 16:07:57 +00:00
|
|
|
import signal
|
2024-01-25 16:39:48 +00:00
|
|
|
import subprocess
|
|
|
|
import threading
|
2024-01-27 05:29:39 +00:00
|
|
|
import time
|
2024-01-25 16:07:57 +00:00
|
|
|
|
2024-01-25 16:07:27 +00:00
|
|
|
|
|
|
|
class ServerThread(threading.Thread):
|
|
|
|
def __init__(self, port, directory):
|
|
|
|
super().__init__()
|
|
|
|
self.port = port
|
|
|
|
self.directory = directory
|
2024-01-25 16:07:57 +00:00
|
|
|
self.process = None
|
2024-01-25 16:21:10 +00:00
|
|
|
self._stop_event = threading.Event()
|
2024-01-25 16:07:27 +00:00
|
|
|
|
|
|
|
def run(self):
|
2024-01-25 16:21:10 +00:00
|
|
|
cmd = ["python", "-m", "http.server", str(self.port)]
|
2024-01-25 16:07:27 +00:00
|
|
|
env = os.environ.copy()
|
2024-01-25 16:07:57 +00:00
|
|
|
env["PWD"] = os.path.expanduser(self.directory)
|
2024-01-25 16:21:10 +00:00
|
|
|
self.process = subprocess.Popen(cmd, env=env, cwd=env["PWD"])
|
|
|
|
|
|
|
|
while not self._stop_event.is_set():
|
|
|
|
self.process.poll()
|
|
|
|
if self.process.returncode is not None:
|
|
|
|
break
|
2024-01-27 05:29:39 +00:00
|
|
|
else:
|
|
|
|
time.sleep(0.2)
|
2024-01-25 16:07:57 +00:00
|
|
|
|
|
|
|
def stop(self):
|
2024-01-25 16:21:10 +00:00
|
|
|
self._stop_event.set()
|
2024-01-25 16:07:57 +00:00
|
|
|
if self.process:
|
|
|
|
self.process.terminate()
|
|
|
|
self.process.wait()
|
2024-01-25 16:07:27 +00:00
|
|
|
|
2024-01-25 16:07:57 +00:00
|
|
|
|
2024-01-25 16:39:48 +00:00
|
|
|
def serve(servers, handle_signals=True):
|
2024-01-25 16:07:27 +00:00
|
|
|
threads = []
|
|
|
|
for port, directory in servers:
|
|
|
|
thread = ServerThread(port, directory)
|
|
|
|
thread.start()
|
|
|
|
threads.append(thread)
|
|
|
|
|
2024-01-25 16:07:57 +00:00
|
|
|
def signal_handler(sig, frame):
|
|
|
|
print("Shutting down servers...")
|
|
|
|
for thread in threads:
|
|
|
|
thread.stop()
|
|
|
|
|
2024-01-25 16:39:48 +00:00
|
|
|
if handle_signals:
|
|
|
|
signal.signal(signal.SIGINT, signal_handler)
|
|
|
|
signal.signal(signal.SIGTERM, signal_handler)
|
2024-01-25 16:07:57 +00:00
|
|
|
|
2024-01-25 16:21:10 +00:00
|
|
|
# Wait for all threads to complete
|
2024-01-25 16:07:27 +00:00
|
|
|
for thread in threads:
|
|
|
|
thread.join()
|
2024-01-25 16:07:57 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
servers = [(8080, "~/server1/out/"), (8081, "~/server2/out/")]
|
|
|
|
serve(servers)
|