用龙卷风处理标准输入 [英] Handling stdin with tornado

查看:92
本文介绍了用龙卷风处理标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何侦听龙卷风循环中stdin上发生的事件?

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

尤其是在龙卷风系统中,我想从标准输入中读取信息,对其作出反应,并在标准输入关闭时终止.同时,Tornado Web服务在同一进程上运行.

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.

在寻找的同时,我能找到的最相似的东西是处理外部产生的进程的流.但是,这不是我想要的:我想处理 current 进程的I/O流,即具有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, i.e. the one that has the web server.

结构上,我的服务器几乎是 hello-world龙卷风,因此我们可以以此为基础建立示例.我只需要添加一个stdin处理程序即可.

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.

推荐答案

您可以在IOLoop实例上使用add_handler方法来监视stdin上的事件.

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()

这篇关于用龙卷风处理标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆