should exit better
This commit is contained in:
parent
88e3a9b148
commit
6693911c00
@ -5,45 +5,32 @@ import signal
|
|||||||
|
|
||||||
|
|
||||||
class ServerThread(threading.Thread):
|
class ServerThread(threading.Thread):
|
||||||
"""
|
|
||||||
A thread for running an HTTP server using subprocess.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, port, directory):
|
def __init__(self, port, directory):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.port = port
|
self.port = port
|
||||||
self.directory = directory
|
self.directory = directory
|
||||||
self.process = None
|
self.process = None
|
||||||
|
self._stop_event = threading.Event()
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
"""
|
cmd = ["python", "-m", "http.server", str(self.port)]
|
||||||
Starts the server and serves files indefinitely using subprocess.
|
|
||||||
"""
|
|
||||||
cmd = f"python -m http.server {self.port}"
|
|
||||||
env = os.environ.copy()
|
env = os.environ.copy()
|
||||||
env["PWD"] = os.path.expanduser(self.directory)
|
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):
|
def stop(self):
|
||||||
"""
|
self._stop_event.set()
|
||||||
Stop the server process if it is running.
|
|
||||||
"""
|
|
||||||
if self.process:
|
if self.process:
|
||||||
self.process.terminate()
|
self.process.terminate()
|
||||||
self.process.wait()
|
self.process.wait()
|
||||||
|
|
||||||
def join(self, timeout=None):
|
|
||||||
"""
|
|
||||||
Stop the server and join the thread.
|
|
||||||
"""
|
|
||||||
self.stop()
|
|
||||||
super().join(timeout)
|
|
||||||
|
|
||||||
|
|
||||||
def serve(servers):
|
def serve(servers):
|
||||||
"""
|
|
||||||
Starts multiple HTTP servers in separate threads using subprocess.
|
|
||||||
"""
|
|
||||||
threads = []
|
threads = []
|
||||||
for port, directory in servers:
|
for port, directory in servers:
|
||||||
thread = ServerThread(port, directory)
|
thread = ServerThread(port, directory)
|
||||||
@ -54,11 +41,10 @@ def serve(servers):
|
|||||||
print("Shutting down servers...")
|
print("Shutting down servers...")
|
||||||
for thread in threads:
|
for thread in threads:
|
||||||
thread.stop()
|
thread.stop()
|
||||||
print("Servers shut down successfully.")
|
|
||||||
|
|
||||||
signal.signal(signal.SIGINT, signal_handler)
|
signal.signal(signal.SIGINT, signal_handler)
|
||||||
signal.signal(signal.SIGTERM, signal_handler)
|
|
||||||
|
|
||||||
|
# Wait for all threads to complete
|
||||||
for thread in threads:
|
for thread in threads:
|
||||||
thread.join()
|
thread.join()
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user