在不同的端口杀死多个 httpservers 运行

Killing multiple httpservers running on different ports

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

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 上停止这些线程。 我该怎么做?

要停止这些服务器之一,您可以使用其 shutdown() 方法。这意味着您需要从捕获 KeyboardInterrupt 的代码中引用服务器。例如:

servers = []
for port in [11111, 22222]:
    servers.append(ThreadingHTTPServer(("localhost",port), Handler))

for server in servers:
    Thread(target=server.serve_forever).start()

try:
    while True:
        time.sleep(1000000)
except KeyboardInterrupt:
    for server in servers:
        server.shutdown()

您可以通过将它们定义为 守护进程线程 来在程序结束时终止大量线程。为此,将他们的 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