python - 杀死在不同端口上运行的多个httpserver

标签 python multithreading python-multithreading socketserver

我使用以下命令启动多个服务器:

from threading import Thread
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        self.wfile.write("Hello World!")

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
    pass

def serve_on_port(port):
    server = ThreadingHTTPServer(("localhost",port), Handler)
    server.serve_forever()

Thread(target=serve_on_port, args=[1111]).start()
Thread(target=serve_on_port, args=[2222]).start()

我想在KeyboardInterrupt上停止这些线程。 我怎样才能做到这一点?

最佳答案

您可以通过将大量线程定义为守护线程,在程序结束时终止它们。为此,请将其 daemon 属性设置为 true。根据the documentation ,

This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

The entire Python program exits when no alive non-daemon threads are left.

所以,像这样的东西应该有效:

for port in [1111, 2222]:
    t = Thread(target=serve_on_port, args=[port])
    t.daemon = True
    t.start()

try:
    while True:
        time.sleep(1000000)
except KeyboardInterrupt:
    pass

请注意,任何非守护进程但仍在运行的线程都会阻止您的程序退出。如果您还希望在退出时杀死其他线程,请在启动它们之前将它们的 daemon 属性设置为 True

关于python - 杀死在不同端口上运行的多个httpserver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28863033/

相关文章:

python - 简单的 python Web 服务器在 Windows 10 上被阻止

javascript - Javascript 中是否可能存在竞争条件? (例如 : I want to get and set value atomically)

java - Commons IO 2.4,如何控制FileAlterationListener的状态并重启

python - python 多线程中的意外行为

Python 线程字符串参数

python - 使用 ALSA 打开带回调的音频

python - 为什么 izip() 的这个实现不起作用?

python - 如何将 Dask.DataFrame 转换为 pd.DataFrame?

python - 为什么 exc_traceback 返回 None

java - Java 的 Thread.sleep 在这里有什么用处?