在多个端口上处理打开python http服务器的更好方法

时间:2015-11-09 14:42:48

标签: python subprocess

我需要在10个端口上打开python http服务器,这是我当前的代码。

self.server_thread = Thread(target=self.start_web_server)
        self.httpd = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER[0]), MyHandler)
        self.httpd1 = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER[1]), MyHandler)
        self.httpd2 = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER[2]), MyHandler)
        self.httpd3 = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER[3]), MyHandler)
        self.httpd4 = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER[4]), MyHandler)
        self.httpd5 = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER[5]), MyHandler)
        self.httpd6 = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER[6]), MyHandler)
        self.httpd7 = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER[7]), MyHandler)
        self.httpd8 = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER[8]), MyHandler)
        self.httpd9 = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER[9]), MyHandler)

我想知道是否有更好的方法将其转换为for循环。

def wait_for_message(self):
        print time.asctime(), "Server Starts"
        self.httpd.serve_forever()
        self.httpd1.serve_forever()
        self.httpd2.serve_forever()
        self.httpd3.serve_forever()
        self.httpd4.serve_forever()
        self.httpd5.serve_forever()
        self.httpd6.serve_forever()
        self.httpd7.serve_forever()
        self.httpd8.serve_forever()
        self.httpd9.serve_forever()

    def stop(self):
        self.httpd.shutdown()
        self.httpd1.shutdown()
        self.httpd2.shutdown()
        self.httpd3.shutdown()
        self.httpd4.shutdown()
        self.httpd5.shutdown()
        self.httpd6.shutdown()
        self.httpd7.shutdown()
        self.httpd8.shutdown()
        self.httpd9.shutdown()
        print time.asctime(), "Server Stops"

另外,这是我的启动和关闭http服务器代码。

这看起来很糟糕,如果我也可以把它变成for循环那么会很好。

谢谢。

1 个答案:

答案 0 :(得分:2)

将服务器放入列表中:

servers = [HTTPServer((HOST_NAME, port_number), MyHandler)
           for port_number in PORT_NUMBER]

在每个线程中启动服务器:

from threading import Thread

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

要优雅地停止所有服务器:

import logging

for httpd in servers:
    try:
        httpd.shutdown()
    except Exception:
        logging.exception("Can't shutdown %r" % (httpd,)) # log exception here