【问题标题】:How to get output in the subprocess in real time?如何实时获取子流程中的输出?
【发布时间】:2020-08-31 20:53:17
【问题描述】:

我正在尝试让 tail -f /var/log/syslog 在变量 data0 中播放结果,但没有成功。

from subprocess import Popen,PIPE
 
def exit_data():
    with Popen(['tail -f', '/var/log/syslog'],stdout=PIPE,stderr=PIPE) as b:
        out,err = b.communicate()
    data0 = out.decode('utf-8')
    return data0

【问题讨论】:

    标签: python python-3.x linux subprocess


    【解决方案1】:

    根据文档,调用communicate() 方法将阻塞,直到子进程退出。由于您正在调用tail -f,因此在tail 进程退出之前不会返回,这只会在EOF、错误等情况下发生。所以您什么都看不到。

    您似乎想在 Python 中连续打印 tail 子进程的输出。为此,您需要启动该过程,并不断(在循环中)从其标准输出中读取并打印结果。不要调用communicate(),而只是从stdout 属性中读取,这是一个标准的类文件对象。

    例如,这个脚本是reader.py:

    import subprocess as sp
    
    # A dummy file to tail
    filename = "/tmp/logfile"
    
    proc = sp.Popen(
        ["tail", "-f", filename],
        stdout=sp.PIPE,
        stderr=sp.PIPE,
        text=True,  # I'm using text files, may not apply to your case
    )
    try:
        while True:
            print(proc.stdout.readline().rstrip("\n"))
    except KeyboardInterrupt:
        print("Received interrupt, exiting")
        proc.terminate()
        proc.wait()
        print("Reaped child")
    

    您可以通过在另一个 Python 脚本中运行以下 sn-p 来测试它的工作原理,称之为 writer.py

    import time
    N_LINES = 100
    
    filename = "/tmp/logfile"
    with open(filename, "wt") as f:
        for _ in range(N_LINES):
            time.sleep(1)
            f.write("a new line of data\n")
            f.flush()
    

    运行它们:

    $ python3 writer.py &
    $ python3 reader.py
    a new line of data
    a new line of data
    a new line of data
    a new line of data
    a new line of data
    ^CReceived interrupt, exiting
    Reaped child
    

    【讨论】:

      猜你喜欢
      • 2020-11-27
      • 2021-01-18
      • 1970-01-01
      • 2022-06-19
      • 2010-10-22
      • 2021-04-15
      • 2015-06-08
      相关资源
      最近更新 更多