简体   繁体   English

用龙卷风处理stdin

[英]Handling stdin with tornado

How to listen for events that happen on stdin in Tornado loop? 如何监听Tornado循环中stdin上发生的事件?

In particular, in a tornado-system, I want to read from stdin, react on it, and terminate if stdin closes. 特别是在龙卷风系统中,我想从stdin读取,对它做出反应,并在stdin关闭时终止。 At the same time, the Tornado web service is running on the same process. 与此同时,Tornado Web服务正在运行相同的进程。

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, ie the one that has the web server. 但是,这不是我想要的:我想处理当前进程的i / o流,即具有Web服务器的进程。

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. 我只需要添加一个stdin处理程序。

You can use the add_handler method on the IOLoop instance to watch for events on stdin . 您可以在IOLoop实例上使用add_handler方法来监视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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM