gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:48:45 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com