should exit better

This commit is contained in:
Michael Pilosov, PhD 2024-01-25 16:21:10 +00:00
parent 88e3a9b148
commit 6693911c00

View File

@ -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()