lazy_serve/lazy_serve.py

55 lines
1.4 KiB
Python
Raw Normal View History

2024-01-25 16:07:27 +00:00
import subprocess
import threading
import os
2024-01-25 16:07:57 +00:00
import signal
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-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:07:27 +00:00
def serve(servers):
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()
signal.signal(signal.SIGINT, signal_handler)
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)