我正在尝试在线程中用python设置一个简单的http服务器。
class MyHandler(SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/shutdown':
print 'Got shutdown request'
self.server.running = False
self.send_response(200)
class Server():
def __init__(self):
self._http_server = HTTPServer(('0.0.0.0', 8123), MyHandler)
self._http_server.running = True
self._http_server_thread = threading.Thread(target = self._run_http_server, name = 'serverthread')
self._http_server_thread.start()
def _run_http_server(self):
print 'Server started'
while( self._http_server.running ):
self._http_server.handle_request()
print 'Server finished serving'
self._http_server.shutdown()
def check_status(self):
l = threading.enumerate()
for i in l:
print i.name
serv = Server()
print 'Sleeping for 20 seconds'
time.sleep(20)
req = urllib2.urlopen('http://127.0.0.1:8123/shutdown')
print 'Finished sleeping'
serv.check()
我的假设是一旦_run_http_server完成运行,线程应该停止运行,但它没有。我得到了这个输出,但线程一直在运行。谁能指出为什么线程不停止?
Server started
Sleeping for 20 seconds
Got shut down request
127.0.0.1 - - [09/Jul/2016 12:17:17] "GET /shutdown HTTP/1.1" 200 -
Server finished serving
Finished sleeping
MainThread
serverthread
True
在代码中,您有自己的请求处理循环(而不是使用 HTTPServer.serve_forever()
)。然而,你打电话给HTTPServer.shutdown()
,他们的工作是告诉serve_forever()
循环停止并等待它停止。由于serve_forever()
甚至没有启动,shutdown()
永远不会返回(它实际上是在等待serve_forever()
启动并立即停止)。删除self._http_server.shutdown()
行可解决此问题。