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):
|
|
|
|
"""
|
|
|
|
A thread for running an HTTP server using subprocess.
|
|
|
|
"""
|
|
|
|
|
|
|
|
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:07:27 +00:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
"""
|
|
|
|
Starts the server and serves files indefinitely using subprocess.
|
|
|
|
"""
|
2024-01-25 16:07:57 +00:00
|
|
|
cmd = f"python -m http.server {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)
|
|
|
|
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()
|
2024-01-25 16:07:27 +00:00
|
|
|
|
|
|
|
def join(self, timeout=None):
|
|
|
|
"""
|
2024-01-25 16:07:57 +00:00
|
|
|
Stop the server and join the thread.
|
2024-01-25 16:07:27 +00:00
|
|
|
"""
|
2024-01-25 16:07:57 +00:00
|
|
|
self.stop()
|
2024-01-25 16:07:27 +00:00
|
|
|
super().join(timeout)
|
|
|
|
|
2024-01-25 16:07:57 +00:00
|
|
|
|
2024-01-25 16:07:27 +00:00
|
|
|
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)
|
|
|
|
|
2024-01-25 16:07:57 +00:00
|
|
|
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)
|
|
|
|
|
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)
|