如何使用 ctrl+c 停止 Tornado Web 服务器? [英] How to stop the tornado web server with ctrl+c?
问题描述
我是龙卷风网络服务器的新手.当我使用 python main_tornado.py 启动 Tornado Web 服务器时,它正在工作.请看下面的代码.
I am new to tornado web server. When I start the tornado web server using python main_tornado.py It is working. Please see the below code.
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
当我使用 CTRL+C 停止服务器时,它给出了以下错误.
When I stop the server using CTRL+C it gave the following error.
^CTraceback (most recent call last):
File "main_tornado.py", line 19, in <module>
tornado.ioloop.IOLoop.instance().start()
File "/home/nyros/Desktop/NewWeb/venv/lib/python3.2/site-packages/tornado/ioloop.py", line 301, in start
event_pairs = self._impl.poll(poll_timeout)
KeyboardInterrupt
请解决我的问题.谢谢..
Please solve my problem. Thanks..
推荐答案
您可以使用 tornado.ioloop.IOLoop.instance().stop()
停止 Tornado 主循环.要在使用 Ctrl+C 传递信号后调用此方法,您可以定期检查全局标志以测试主循环是否应该结束并为 SIGINT 信号注册处理程序,这将改变这个标志:
You can stop Tornado main loop with tornado.ioloop.IOLoop.instance().stop()
. To have this method called after passing signal with Ctrl+C you can periodically check global flag to test if main loop should end and register handler for SIGINT signal which will change value of this flag:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import signal
import logging
import tornado.ioloop
import tornado.web
import tornado.options
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
class MyApplication(tornado.web.Application):
is_closing = False
def signal_handler(self, signum, frame):
logging.info('exiting...')
self.is_closing = True
def try_exit(self):
if self.is_closing:
# clean up here
tornado.ioloop.IOLoop.instance().stop()
logging.info('exit success')
application = MyApplication([
(r"/", MainHandler),
])
if __name__ == "__main__":
tornado.options.parse_command_line()
signal.signal(signal.SIGINT, application.signal_handler)
application.listen(8888)
tornado.ioloop.PeriodicCallback(application.try_exit, 100).start()
tornado.ioloop.IOLoop.instance().start()
输出:
$ python test.py
[I 181209 22:13:43 web:2162] 200 GET / (127.0.0.1) 0.92ms
^C[I 181209 22:13:45 test:21] exiting...
[I 181209 22:13:45 test:28] exit success
<小时>
更新
我刚刚看到问题龙卷风长轮询请求这个简单的解决方案:
I've just saw in question Tornado long polling requests this simple solution:
try:
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
tornado.ioloop.IOLoop.instance().stop()
显然,这是一种不太安全的方式.
Obviously, this is a less safe way.
更新
编辑了代码以删除global
的使用.
Edited the code to remove use of global
.
这篇关于如何使用 ctrl+c 停止 Tornado Web 服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!