gpt4 book ai didi

python - 通过tornado.proces.Subprocess调用xtail

转载 作者:行者123 更新时间:2023-12-01 04:29:28 30 4
gpt4 key购买 nike

如何通过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()

我想收集一些日志文件夹中的日志变化,准备使用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 读取。

关于python - 通过tornado.proces.Subprocess调用xtail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32577435/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com