简体   繁体   English

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

[英]How to get output in the subprocess in real time?

I'm trying to get tail -f /var/log/syslog to play the result in variable data0 but without success.我试图让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

From the documentation, calling the communicate() method will block until the child process exits.从文档中,调用communicate()方法将阻塞,直到子进程退出。 Since you're calling tail -f , this will not return until the tail process exits, which only happens on EOF, errors, etc. So you don't see anything.由于您正在调用tail -f ,直到tail进程退出时才会返回,这只会在 EOF、错误等情况下发生。所以您什么都看不到。

It looks like you want to continuously print the output of the tail subprocess in Python. To do this, you'd need to start the process, and continually (in a loop) read from its stdout and print the result.看起来您想在 Python 中连续打印tail子进程的 output。为此,您需要启动该进程,并不断(在循环中)从其标准输出读取并打印结果。 Do not call communicate() , and instead just read from the stdout attribute, which is a standard file-like object.不要调用communicate() ,而只是从stdout属性读取,这是一个标准文件,如 object。

For example, this script would be reader.py :例如,此脚本为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")

You can test this works by running the following snippet in another Python script, call it writer.py :您可以通过在另一个 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()

Run them with:运行它们:

$ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM