【问题标题】:Python subprocess readingPython子进程读取
【发布时间】:2011-04-21 14:28:05
【问题描述】:

有这个代码

p = subprocess.Popen('tail -f /var/log/syslog', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

for line in p.stdout.readlines():
    print line,
    time.sleep(1)

即使我在 syslog 中添加一些内容,脚本也会挂起并且不写入任何行。

为什么?

【问题讨论】:

  • 我必须在另一个线程中运行 Popen 吗?

标签: python subprocess


【解决方案1】:

readlines() 不会返回,直到进程中有一个 eof,因为 tail 不会在没有中断的情况下完成。

您可以将循环更改为:

while True:
    print(p.stdout.readline())

除非您希望每行之间有额外的 1s 间隔,否则无需睡眠,因为 readline 会阻塞,使用最少的资源,直到有完整的行可用。

【讨论】:

  • 嘿@linuts,我正在做类似的事情,但一段时间后,我在'p.stdout.readline()'中没有得到任何东西,如果我从命令行手动拖尾文件,它会一直等待,日志还在来。内联haproxy_log_file = '/tmp/filebeat/filebeat' f = subprocess.Popen(['sudo','tail','-F',haproxy_log_file],stdout=subprocess.PIPE,stderr=subprocess.PIPE) while True: line = f.stdout.readline()
【解决方案2】:

您也可以直接在 python 中模拟tail -f

检查这个:tail -f in Python (Python recipe)

或此:Emulate the "tail -f" command 或 Google 以获取更多示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-01
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 2014-02-10
    • 2015-08-05
    • 2015-01-20
    相关资源
    最近更新 更多