lazy_serve/lazy_serve.py
Michael Pilosov, PhD 06aa9a2dce initial commit
2024-01-25 16:07:27 +00:00

81 lines
1.9 KiB
Python

"""
lazy_serve.py
-------------
A simple package for effortlessly starting HTTP servers.
Example usage:
---------------
import lazy_serve as lz
if __name__ == "__main__":
servers = [(8080, "~/server1/out/"), (8081, "~/server2/out/")]
lz.serve(servers)
"""
import subprocess
import threading
import os
class ServerThread(threading.Thread):
"""
A thread for running an HTTP server using subprocess.
Parameters
----------
port : int
The port number on which the server will listen.
directory : str
The directory from which the server will serve files.
Attributes
----------
port : int
The port number on which the server will listen.
directory : str
The directory from which the server will serve files.
"""
def __init__(self, port, directory):
super().__init__()
self.port = port
self.directory = directory
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 join(self, timeout=None):
"""
Stop the server.
"""
self.process.terminate()
super().join(timeout)
def serve(servers):
"""
Starts multiple HTTP servers in separate threads using subprocess.
Parameters
----------
servers : list of tuple
A list of tuples, each containing a port number and a directory path.
Example
-------
>>> serve([(8080, '~/mydir'), (8081, '~/myotherdir')])
"""
threads = []
for port, directory in servers:
thread = ServerThread(port, directory)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()