通过 tornado.proces.Subprocess 调用 xtail

call xtail by tornado.proces.Subprocess

如何通过 tornado.proces.Subprocess 调用 xtail

import subprocess

from tornado.ioloop import IOLoop
from tornado import gen
from tornado import process

class Reader(object):
    def __init__(self, xwatch_path, max_idle=600, ioloop=None):
        self.xwatch_path = xwatch_path
        self.ioloop = ioloop
        self.max_idle = max_idle

    @gen.coroutine
    def call_subprocess(self, cmd, stdin_data=None, stdin_async=False):
        stdin = STREAM if stdin_async else subprocess.PIPE
        sub_process = process.Subprocess(
            cmd, stdin=stdin, stdout=STREAM, stderr=STREAM, io_loop=self.ioloop
        )

        if stdin_data:
            if stdin_async:
                yield gen.Task(sub_process.stdin.write, stdin_data)
            else:
                sub_process.stdin.write(stdin_data)
        if stdin_async or stdin_data:
            sub_process.stdin.close()
        result, error = yield [
            gen.Task(sub_process.stdout.read_until, '\n'),
            gen.Task(sub_process.stderr.read_until, '\n')
        ]
        print result
        raise gen.Return((result, error))

    @gen.coroutine
    def popen(self):
        while True:
            result, error = yield self.call_subprocess(['xtail', self.xwatch_path])

            print result, error

def read_log(ioloop):
    access_reader = AccessLogReader(
        '/home/vagrant/logs')


    ioloop.add_callback(access_reader.popen)


def main():
    ioloop = IOLoop.instance()
    read_log(ioloop)
    ioloop.start()


if __name__ == '__main__':
    main()

我想收集几条日志变化到log文件夹里,准备用xtail多文件夹收集日志,然后自己开发环境调试。

我用Vim修改了~/log/123.txt文件,但是看不到输出结果

声明

result, error = yield [
    gen.Task(sub_process.stdout.read_until, '\n'),
    gen.Task(sub_process.stderr.read_until, '\n')
]

读取进程的一行标准输出和一行标准错误,并阻塞直到它读取了这两行。如果 xtail 只写入两个流之一,这将永远不会完成。

你可能想循环阅读(注意 gen.Task 不是必需的):

@gen.coroutine
def read_from_stream(stream):
    try:
        while True:
            line = yield stream.read_until('\n')
            print(line)
    except StreamClosedError:
        return

如果您关心 stdout 和 stderr 之间的区别,请分别阅读它们。这将在每个流到达时打印行,并在两个流都关闭时停止:

yield [read_from_stream(sub_process.stdout), read_from_stream(sub_process.stderr)]

如果不这样做,则在创建子流程时通过传递 stdout=STREAM, stderr=subprocess.STDOUT 来合并它们,并且只从 sub_process.stdout.

中读取