signal exit handling

This commit is contained in:
Michael Pilosov, PhD 2024-01-25 16:07:57 +00:00
parent 06aa9a2dce
commit 88e3a9b148
2 changed files with 40 additions and 52 deletions

View File

@ -1,74 +1,48 @@
"""
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 subprocess
import threading import threading
import os import os
import signal
class ServerThread(threading.Thread): class ServerThread(threading.Thread):
""" """
A thread for running an HTTP server using subprocess. 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): def __init__(self, port, directory):
super().__init__() super().__init__()
self.port = port self.port = port
self.directory = directory self.directory = directory
self.process = None
def run(self): def run(self):
""" """
Starts the server and serves files indefinitely using subprocess. Starts the server and serves files indefinitely using subprocess.
""" """
cmd = f'python -m http.server {self.port}' 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, 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()
def join(self, timeout=None): def join(self, timeout=None):
""" """
Stop the server. Stop the server and join the thread.
""" """
self.process.terminate() self.stop()
super().join(timeout) super().join(timeout)
def serve(servers): def serve(servers):
""" """
Starts multiple HTTP servers in separate threads using subprocess. 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 = [] threads = []
for port, directory in servers: for port, directory in servers:
@ -76,5 +50,19 @@ def serve(servers):
thread.start() thread.start()
threads.append(thread) threads.append(thread)
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)
for thread in threads: for thread in threads:
thread.join() thread.join()
if __name__ == "__main__":
servers = [(8080, "~/server1/out/"), (8081, "~/server2/out/")]
serve(servers)

View File

@ -1,15 +1,15 @@
from setuptools import setup, find_packages from setuptools import setup, find_packages
setup( setup(
name='lazy_serve', name="lazy_serve",
version='0.1', version="0.1",
description='A simple package for effortlessly starting HTTP servers.', description="A simple package for effortlessly starting HTTP servers.",
long_description=open('README.md').read(), long_description=open("README.md").read(),
long_description_content_type='text/markdown', long_description_content_type="text/markdown",
author='Your Name', author="Your Name",
author_email='your.email@example.com', author_email="your.email@example.com",
url='https://github.com/yourusername/lazy_serve', url="https://github.com/yourusername/lazy_serve",
packages=find_packages(), packages=find_packages(),
install_requires=[], install_requires=[],
python_requires='>=3.6', python_requires=">=3.6",
) )