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

后端 未结 4 1463
北荒
北荒 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:54

    I'd say the cleanest, safest and most portable solution would be to put all closing and clean-up calls in a finally block instead of relying on KeyboardInterrupt exception:

    import tornado.ioloop
    import tornado.web
    
    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            self.write("Hello, world")
    
    application = tornado.web.Application([
        (r"/", MainHandler),
    ])
    
    # .instance() is deprecated in Tornado 5
    loop = tornado.ioloop.IOLoop.current()
    
    if __name__ == "__main__":
        try:
            print("Starting server")
            application.listen(8888)
            loop.start()
        except KeyboardInterrupt:
            pass
        finally:
            loop.stop()       # might be redundant, the loop has already stopped
            loop.close(True)  # needed to close all open sockets
        print("Server shut down, exiting...")
    

提交回复
热议问题