lazy_serve/lazy_serve.py
2024-01-25 16:39:48 +00:00

57 lines
1.5 KiB
Python

import os
import signal
import subprocess
import threading
class ServerThread(threading.Thread):
def __init__(self, port, directory):
super().__init__()
self.port = port
self.directory = directory
self.process = None
self._stop_event = threading.Event()
def run(self):
cmd = ["python", "-m", "http.server", str(self.port)]
env = os.environ.copy()
env["PWD"] = os.path.expanduser(self.directory)
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
def stop(self):
self._stop_event.set()
if self.process:
self.process.terminate()
self.process.wait()
def serve(servers, handle_signals=True):
threads = []
for port, directory in servers:
thread = ServerThread(port, directory)
thread.start()
threads.append(thread)
def signal_handler(sig, frame):
print("Shutting down servers...")
for thread in threads:
thread.stop()
if handle_signals:
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# Wait for all threads to complete
for thread in threads:
thread.join()
if __name__ == "__main__":
servers = [(8080, "~/server1/out/"), (8081, "~/server2/out/")]
serve(servers)