lazy_serve/lazy_serve.py
Michael Pilosov, PhD 88e3a9b148 signal exit handling
2024-01-25 16:07:57 +00:00

69 lines
1.7 KiB
Python

import subprocess
import threading
import os
import signal
class ServerThread(threading.Thread):
"""
A thread for running an HTTP server using subprocess.
"""
def __init__(self, port, directory):
super().__init__()
self.port = port
self.directory = directory
self.process = None
def run(self):
"""
Starts the server and serves files indefinitely using subprocess.
"""
cmd = f"python -m http.server {self.port}"
env = os.environ.copy()
env["PWD"] = os.path.expanduser(self.directory)
self.process = subprocess.Popen(cmd, shell=True, env=env, cwd=env["PWD"])
def stop(self):
"""
Stop the server process if it is running.
"""
if self.process:
self.process.terminate()
self.process.wait()
def join(self, timeout=None):
"""
Stop the server and join the thread.
"""
self.stop()
super().join(timeout)
def serve(servers):
"""
Starts multiple HTTP servers in separate threads using subprocess.
"""
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()
print("Servers shut down successfully.")
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
for thread in threads:
thread.join()
if __name__ == "__main__":
servers = [(8080, "~/server1/out/"), (8081, "~/server2/out/")]
serve(servers)