根据文档,调用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