How to stop the tornado web server with ctrl+c?

后端 未结 4 1461
北荒
北荒 2021-02-05 13:21

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
         


        
4条回答
  •  既然无缘
    2021-02-05 13:35

    You can simply stop the Tornado ioloop from a signal handler. It should be safe thanks to add_callback_from_signal() method, the event loop will exit nicely, finishing any eventually concurrently running task.

    import tornado.ioloop
    import tornado.web
    import signal
    
    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            self.write("Hello, world")
    
    application = tornado.web.Application([
        (r"/", MainHandler),
    ])
    
    def sig_exit(signum, frame):
        tornado.ioloop.IOLoop.instance().add_callback_from_signal(do_stop)
    
    def do_stop(signum, frame):
        tornado.ioloop.IOLoop.instance().stop()
    
    if __name__ == "__main__":
        application.listen(8888)
        signal.signal(signal.SIGINT, sig_exit)
        tornado.ioloop.IOLoop.instance().start()
    

提交回复
热议问题