我希望能夠停止並重新啓動Tornado服務器以進行測試和演示。但它似乎並未釋放該端口。如何停止(並重新啓動!)Tornado服務器?
以下代碼基於answer showing how to properly stop Tornado。我只是在底部添加了代碼,試圖重啓Tornado。它失敗,出現「錯誤:地址正在使用」異常。我甚至加了一個電話給ioloop.close()
但這並沒有幫助。
#! /usr/bin/env python
import threading
import tornado.ioloop
import tornado.web
import time
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world!\n")
def start_tornado(*args, **kwargs):
application = tornado.web.Application([
(r"/", MainHandler),
])
application.listen(8888)
print "Starting Torando"
tornado.ioloop.IOLoop.instance().start()
print "Tornado finished"
def stop_tornado():
ioloop = tornado.ioloop.IOLoop.instance()
ioloop.add_callback(ioloop.stop)
ioloop.add_callback(ioloop.close) # I added this but it didn't help.
print "Asked Tornado to exit"
def main():
t = threading.Thread(target=start_tornado)
t.start()
time.sleep(1)
stop_tornado()
t.join()
print "Tornado thread stopped."
t = threading.Thread(target=start_tornado) # Attempt restart.
t.start()
if __name__ == "__main__":
main()
輸出:
Starting Torando
Asked Tornado to exit
Tornado finished
Tornado thread stopped.
Exception in thread Thread-2:
Traceback (most recent call last):
File "/home/mudd/musl/Python-2.7.11.install/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/home/mudd/musl/Python-2.7.11.install/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "./test_tonado_restart.py", line 17, in start_tornado
application.listen(8888)
File "/home/mudd/musl/Python-2.7.11.install/lib/python2.7/site-packages/tornado/web.py", line 1825, in listen
server.listen(port, address)
File "/home/mudd/musl/Python-2.7.11.install/lib/python2.7/site-packages/tornado/tcpserver.py", line 126, in listen
sockets = bind_sockets(port, address=address)
File "/home/mudd/musl/Python-2.7.11.install/lib/python2.7/site-packages/tornado/netutil.py", line 196, in bind_sockets
sock.bind(sockaddr)
File "/home/mudd/musl/Python-2.7.11.install/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
error: [Errno 98] Address in use
我不認爲你需要在龍捲風來管理你自己的線程。 ioloop爲你做到了這一點,我認爲 –