如何从Python中的请求处理程序中关闭HTTPServer?

时间:2013-09-26 22:56:53

标签: python basehttpserver

收到StopIteration异常后,如何关闭此服务器? sys.exit()不起作用。

#!/usr/bin/env python

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

PORT_NUMBER = 2000

from itertools import islice
filename = 'data/all.txt'
file = open(filename, 'r')
lines_gen = islice(file, None)

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        global lines_gen

        self.send_response(200)
        self.send_header('Content-type','text/plain')
        self.end_headers()

        try:
            for i in range(10):
                next_line = lines_gen.next()
                self.wfile.write(next_line)
        except StopIteration:
            # return response and shutdown the server
            # ?????

        return

try:
    server = HTTPServer(('', PORT_NUMBER), MyHandler)
    print('Started httpserver on port ' , PORT_NUMBER)
    server.serve_forever()

except KeyboardInterrupt:
    print('^C received, shutting down the web server')
    server.socket.close()

1 个答案:

答案 0 :(得分:15)

只需在第二个帖子中调用shutdown()

# return response and shutdown the server
import threading
assassin = threading.Thread(target=server.shutdown)
assassin.daemon = True
assassin.start()