From 6693911c00a421631d053bfae29eed853540a606 Mon Sep 17 00:00:00 2001 From: "Michael Pilosov, PhD" Date: Thu, 25 Jan 2024 16:21:10 +0000 Subject: [PATCH] should exit better --- lazy_serve.py | 34 ++++++++++------------------------ 1 file changed, 10 insertions(+), 24 deletions(-) diff --git a/lazy_serve.py b/lazy_serve.py index 1bda6bc..bce8274 100644 --- a/lazy_serve.py +++ b/lazy_serve.py @@ -5,45 +5,32 @@ 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 + self._stop_event = threading.Event() def run(self): - """ - Starts the server and serves files indefinitely using subprocess. - """ - cmd = f"python -m http.server {self.port}" + cmd = ["python", "-m", "http.server", str(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"]) + 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): - """ - Stop the server process if it is running. - """ + self._stop_event.set() 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) @@ -54,11 +41,10 @@ def serve(servers): 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) + # Wait for all threads to complete for thread in threads: thread.join()