使用tornado处理标准输入(stdin)

3
如何在Tornado循环中监听stdin发生的事件?
特别是,在tornado系统中,我想从stdin读取数据,做出反应,并在stdin关闭时终止。同时,Tornado Web服务正在同一进程上运行。
在寻找这个问题的解决方法时,我发现了处理外部生成进程流的最相似的方法。然而,这不是我想要的:我想要处理当前进程的输入/输出流,即具有Web服务器的进程。
从结构上看,我的服务器与hello-world tornado非常相似,因此我们可以以此为例。我只需要添加一个stdin处理程序。
1个回答

6
你可以在IOLoop实例上使用add_handler方法来监听stdin上的事件。
以下是一个最小工作示例:
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()

谢谢!获取套接字数据已经足够了。不过,我很难捕获“stdin关闭”事件。在这里发布了后续问题:http://stackoverflow.com/questions/35741435/handling-closing-of-stdin-with-tornado - Motiejus Jakštys
给我 ogram Files (x86)\Python35-32\workspace\webSocketServer.py == Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\workspace\webSocketServer.py", line 38, in <module> tornado.ioloop.IOLoop.instance().add_handler(sys.stdin, on_stdin, tornado.ioloop.IOLoop.READ) File "C:\Program Files (x86)\Python35-32\lib\site-packages\tornado\ioloop.py", line 719, in add_handler fd, obj = self.split_fd(fd) File "C:\Program Files (x86)\Python35-32\lib\site-packages\tornado\ioloop.py", line 648, in split_fd return fd.fileno(), fd io.UnsupportedOperation: fileno - Stefan Höltker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接