使用子进程获取实时输出

时间:2009-04-29 16:45:48

标签: python subprocess

我正在尝试为命令行程序(svnadmin verify)编写一个包装器脚本,它将为操作显示一个很好的进度指示器。这要求我能够在输出后立即查看包装程序的每一行输出。

我认为我只是使用subprocess.Popen执行程序,使用stdout=PIPE,然后在进入时读取每一行并相应地对其进行操作。但是,当我运行以下代码时,输​​出似乎在某处缓冲,导致它出现在两个块中,第1行到第332行,然后是333到439(最后一行输出)

from subprocess import Popen, PIPE, STDOUT

p = Popen('svnadmin verify /var/svn/repos/config', stdout = PIPE, 
        stderr = STDOUT, shell = True)
for line in p.stdout:
    print line.replace('\n', '')

稍微查看子进程的文档后,我发现了bufsize的{​​{1}}参数,所以我尝试将bufsize设置为1(缓冲每一行)和0(无缓冲区),但都没有价值似乎改变了线路的传递方式。

此时我开始掌握吸管,所以我编写了以下输出循环:

Popen

但得到了同样的结果。

是否可以获得使用子进程执行的程序的“实时”程序输出? Python中还有一些其他选项是向前兼容的(不是while True: try: print p.stdout.next().replace('\n', '') except StopIteration: break )吗?

19 个答案:

答案 0 :(得分:75)

我尝试了这个,并且出于某种原因,而代码

for line in p.stdout:
  ...

积极缓冲,变种

while True:
  line = p.stdout.readline()
  if not line: break
  ...

没有。显然这是一个已知的错误:http://bugs.python.org/issue3907(该问题现在已于2018年8月29日“关闭”)

答案 1 :(得分:35)

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    print line,
p.stdout.close()
p.wait()

答案 2 :(得分:18)

你可以试试这个:

import subprocess
import sys

process = subprocess.Popen(
    cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)

while True:
    out = process.stdout.read(1)
    if out == '' and process.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()

如果使用readline而不是read,则会出现一些未打印输入消息的情况。尝试使用命令,需要内联输入并亲自查看。

答案 3 :(得分:15)

您可以直接将子流程输出定向到流。简化示例:

subprocess.run(['ls'], stderr=sys.stderr, stdout=sys.stdout)

答案 4 :(得分:3)

我在一段时间后遇到了同样的问题。我的解决方案是抛弃read方法的迭代,即使你的子进程没有完成执行,它也将立即返回。

答案 5 :(得分:2)

您可以在子进程的输出中的每个字节上使用迭代器。这允许从子进程进行内联更新(以' \ r'覆盖前一个输出行结束的行):

from subprocess import PIPE, Popen

command = ["my_command", "-my_arg"]

# Open pipe to subprocess
subprocess = Popen(command, stdout=PIPE, stderr=PIPE)


# read each byte of subprocess
while subprocess.poll() is None:
    for c in iter(lambda: subprocess.stdout.read(1) if subprocess.poll() is None else {}, b''):
        c = c.decode('ascii')
        sys.stdout.write(c)
sys.stdout.flush()

if subprocess.returncode != 0:
    raise Exception("The subprocess did not terminate correctly.")

答案 6 :(得分:2)

实时输出问题已解决: 我在Python中遇到过类似的问题,同时从c程序中捕获实时输出。我添加了" fflush(stdout);"在我的C代码中。它对我有用。这是剪辑代码

<< C程序>>

#include <stdio.h>
void main()
{
    int count = 1;
    while (1)
    {
        printf(" Count  %d\n", count++);
        fflush(stdout);
        sleep(1);
    }
}

&LT;&LT; Python程序&gt;&gt;

#!/usr/bin/python

import os, sys
import subprocess


procExe = subprocess.Popen(".//count", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

while procExe.poll() is None:
    line = procExe.stdout.readline()
    print("Print:" + line)

&LT;&LT; OUTPUT&GT;&GT; 打印:计数1 打印:计数2 打印:数3

希望它有所帮助。

〜sairam

答案 7 :(得分:1)

我使用此解决方案在子进程上获得实时输出。一旦进程完成,该循环将停止,从而不需要break语句或可能的无限循环。

sub_process = subprocess.Popen(my_command, close_fds=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while sub_process.poll() is None:
    out = sub_process.stdout.read(1)
    sys.stdout.write(out)
    sys.stdout.flush()

答案 8 :(得分:1)

发现这个&#34;即插即用&#34;函数here。工作就像一个魅力!

import subprocess

def myrun(cmd):
    """from http://blog.kagesenshi.org/2008/02/teeing-python-subprocesspopen-output.html
    """
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout = []
    while True:
        line = p.stdout.readline()
        stdout.append(line)
        print line,
        if line == '' and p.poll() != None:
            break
    return ''.join(stdout)

答案 9 :(得分:1)

将pexpect [http://www.noah.org/wiki/Pexpect]与非阻塞读取线一起使用可以解决此问题。它源于管道被缓冲的事实,因此你的应用程序的输出被管道缓冲,因此在缓冲区填充或进程死亡之前你无法获得该输出。

答案 10 :(得分:1)

根据使用情况,您可能还希望在子流程本身中禁用缓冲。

如果子进程将是Python进程,则可以在调用之前执行此操作:

os.environ["PYTHONUNBUFFERED"] = "1"

或者将其在env参数中传递给Popen

否则,如果您使用的是Linux / Unix,则可以使用stdbuf工具。例如。喜欢:

cmd = ["stdbuf", "-oL"] + cmd

另请参见here关于stdbuf或其他选项。

(有关相同答案,另请参见here。)

答案 11 :(得分:1)

在Python 3.x中,该过程可能会挂起,因为输出是字节数组而不是字符串。确保将其解码为字符串。

从Python 3.6开始,您可以使用Popen Constructor中的参数encoding来实现。完整的示例:

process = subprocess.Popen(
    'my_command',
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    shell=True,
    encoding='utf-8',
    errors='replace'
)

while True:
    realtime_output = process.stdout.readline()

    if realtime_output == '' and process.poll() is not None:
        break

    if realtime_output:
        print(realtime_output.strip(), flush=True)

请注意,此代码redirects stderrstdouthandles output errors

答案 12 :(得分:0)

完整的解决方案:

import contextlib
import subprocess

# Unix, Windows and old Macintosh end-of-line
newlines = ['\n', '\r\n', '\r']
def unbuffered(proc, stream='stdout'):
    stream = getattr(proc, stream)
    with contextlib.closing(stream):
        while True:
            out = []
            last = stream.read(1)
            # Don't loop forever
            if last == '' and proc.poll() is not None:
                break
            while last not in newlines:
                # Don't loop forever
                if last == '' and proc.poll() is not None:
                    break
                out.append(last)
                last = stream.read(1)
            out = ''.join(out)
            yield out

def example():
    cmd = ['ls', '-l', '/']
    proc = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        # Make all end-of-lines '\n'
        universal_newlines=True,
    )
    for line in unbuffered(proc):
        print line

example()

答案 13 :(得分:0)

这是我一直用来做的基本骨架。它可以轻松实现超时,并能够处理不可避免的悬挂过程。

import subprocess
import threading
import Queue

def t_read_stdout(process, queue):
    """Read from stdout"""

    for output in iter(process.stdout.readline, b''):
        queue.put(output)

    return

process = subprocess.Popen(['dir'],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT,
                           bufsize=1,
                           cwd='C:\\',
                           shell=True)

queue = Queue.Queue()
t_stdout = threading.Thread(target=t_read_stdout, args=(process, queue))
t_stdout.daemon = True
t_stdout.start()

while process.poll() is None or not queue.empty():
    try:
        output = queue.get(timeout=.5)

    except Queue.Empty:
        continue

    if not output:
        continue

    print(output),

t_stdout.join()

答案 14 :(得分:0)

Streaming subprocess stdin and stdout with asyncio in PythonKevin McCarthy博客文章显示了如何使用asyncio:

import asyncio
from asyncio.subprocess import PIPE
from asyncio import create_subprocess_exec


async def _read_stream(stream, callback):
    while True:
        line = await stream.readline()
        if line:
            callback(line)
        else:
            break


async def run(command):
    process = await create_subprocess_exec(
        *command, stdout=PIPE, stderr=PIPE
    )

    await asyncio.wait(
        [
            _read_stream(
                process.stdout,
                lambda x: print(
                    "STDOUT: {}".format(x.decode("UTF8"))
                ),
            ),
            _read_stream(
                process.stderr,
                lambda x: print(
                    "STDERR: {}".format(x.decode("UTF8"))
                ),
            ),
        ]
    )

    await process.wait()


async def main():
    await run("docker build -t my-docker-image:latest .")


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

答案 15 :(得分:0)

(此解决方案已通过Python 2.7.15测试)
每行读/写后只需要sys.stdout.flush():

while proc.poll() is None:
    line = proc.stdout.readline()
    sys.stdout.write(line)
    # or print(line.strip()), you still need to force the flush.
    sys.stdout.flush()

答案 16 :(得分:0)

很少有建议使用python 3.x或pthon 2.x的答案,下面的代码对两者都适用。

 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,)
    stdout = []
    while True:
        line = p.stdout.readline()
        if not isinstance(line, (str)):
            line = line.decode('utf-8')
        stdout.append(line)
        print (line)
        if (line == '' and p.poll() != None):
            break

答案 17 :(得分:0)

如果您只是想将日志实时转发到控制台

下面的代码对两者都适用

 p = subprocess.Popen(cmd,
                         shell=True,
                         cwd=work_dir,
                         bufsize=1,
                         stdin=subprocess.PIPE,
                         stderr=sys.stderr,
                         stdout=sys.stdout)

答案 18 :(得分:0)

<div class="holder">
  <div class="group1">...</div>
  <div class="group2">.....</div>
</div>
相关问题