龙卷风和tornado.iostream.PipeIOStream

时间:2014-09-21 14:43:58

标签: python asynchronous tornado

我需要通过服务器中某些文件的2eb套接字进行异步交互式日志操作(当事情发生并写入时读取),但首先我想了解如何以交互方式和异步方式读取和写入文件。

我还在阅读"阅读"一部分。

如果我执行以下代码,同时打开控制台并通过

写入
echo foo > file.txt

我期待在龙卷风控制台中发生一些事情。但是......没什么。一些忠告?该文档不包含任何关于tornado.iostream.PipeIOStream的示例(或者我没有找到它们)

import os

import tornado.ioloop
import tornado.web

clientpath = '../client'
port = 8888


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")


def tail(data):
    print "> ", data, " ."

if __name__ == "__main__":
    settings = {
        "template_path": os.path.join(os.path.dirname(__file__), clientpath)
    }

    handlers = [
        (r"/", MainHandler),
    ]

    fd = open("file.txt")
    stream = tornado.iostream.PipeIOStream(fd.fileno())
    stream.read_until('\n', tail)

    application = tornado.web.Application(handlers, **settings)
    application.listen(port)
    tornado.ioloop.IOLoop.instance().start()

2 个答案:

答案 0 :(得分:2)

底层系统调用(select,epoll等)并不真正支持常规文件,因此PipeIOStream也不支持。它们足够近以至于它有时看起来像是在工作,但是当文件发生变化并且文件末尾有不同的行为时,您实际上无法获得通知。您应该使用管道或套接字进行进程间通信,而不是常规文件。

要模仿tail -f的行为,请定期使用add_timeoutPeriodicCallback定位文件,并在尺寸发生变化时从中读取(全部为tail -f直到最近才在大多数系统上做过)。您还可以使用inotify更有效地发现文件何时发生更改,尽管将与Tornado集成inotify仍留作读者练习。

答案 1 :(得分:0)

我知道这个问题还很老,但是aiofiles库的设计恰好能够异步进行磁盘读取,并且可以使它与龙卷风事件循环配合得很好。