如何实时获取子进程中的输出?

How to get output in the subprocess in real time?

我试图让 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

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

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

例如,此脚本为 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