Search code examples
pythonpipetornado

Handling stdin with tornado


How to listen for events that happen on stdin in Tornado loop?

In particular, in a tornado-system, I want to read from stdin, react on it, and terminate if stdin closes. At the same time, the Tornado web service is running on the same process.

While looking for this, the most similar I could find was handling streams of an externally spawned process. However, this is not what I want: I want to handle i/o stream of the current process, i.e. the one that has the web server.

Structurally, my server is pretty much hello-world tornado, so we can base the example off that. I just need to add an stdin handler.


Solution

  • You can use the add_handler method on the IOLoop instance to watch for events on stdin.

    Here's a minimal working example:

    from tornado.ioloop import IOLoop
    from tornado.web import Application, RequestHandler
    import sys
    
    class MainHandler(RequestHandler):
    
        def get(self):
    
            self.finish("foo")
    
    application = Application([
        (r"/", MainHandler),
    ])
    
    def on_stdin(fd, events):
    
        content = fd.readline()
    
        print "received: %s" % content
    
    if __name__ == "__main__":
    
        application.listen(8888)
    
        IOLoop.instance().add_handler(sys.stdin, on_stdin, IOLoop.READ)
    
        IOLoop.instance().start()