如何在子流程中实时获取输出?

时间:2020-08-31 20:53:17

标签: python python-3.x linux subprocess

我正在尝试获取 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

1 个答案:

答案 0 :(得分:0)

在文档中,调用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脚本中运行以下代码段(称为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
相关问题