156

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

我想我只需使用subprocess.Popen, use来执行程序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', '')

在看了一些关于 subprocess 的文档之后,我发现了bufsizeto 的参数Popen,所以我尝试将 bufsize 设置为 1(每行缓冲)和 0(无缓冲),但是这两个值似乎都没有改变传递行的方式。

在这一点上,我开始抓住稻草,所以我编写了以下输出循环:

while True:
    try:
        print p.stdout.next().replace('\n', '')
    except StopIteration:
        break

但得到了相同的结果。

是否可以获得使用子进程执行的程序的“实时”程序输出?Python 中是否还有其他向前兼容的选项(不是exec*)?

4

20 回答 20

87

我试过这个,由于某种原因,代码

for line in p.stdout:
  ...

积极缓冲,变体

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

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

于 2009-04-29T17:26:53.640 回答
39

通过将缓冲区大小设置为 1,您实际上强制进程不缓冲输出。

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    print line,
p.stdout.close()
p.wait()
于 2011-06-20T16:13:51.240 回答
33

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

subprocess.run(['ls'], stderr=sys.stderr, stdout=sys.stdout)
于 2018-02-21T08:17:06.397 回答
25

你可以试试这个:

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,会出现输入信息不打印的情况。尝试使用需要内联输入的命令并亲自查看。

于 2009-04-29T17:21:10.203 回答
11

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

从 Python 3.6 开始,您可以使用Popen Constructorencoding中的参数来完成。完整的例子:

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)

请注意,此代码重定向 stderrstdout处理输出错误

于 2019-09-17T08:49:38.963 回答
10

实时输出问题已解决:我在 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);
    }
}

蟒蛇程序:

#!/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)

输出:

Print: Count  1
Print: Count  2
Print: Count  3
于 2015-05-13T12:26:10.653 回答
8

Kevin McCarthy在 Python博客文章中使用 asyncio的Streaming subprocess stdin 和 stdout展示了如何使用 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())
于 2018-11-15T16:21:29.623 回答
4

根据用例,您可能还希望禁用子进程本身的缓冲。

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

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

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

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

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

另请参阅此处关于stdbuf或其他选项。

(有关相同的答案,请参见此处。)

于 2018-10-17T09:14:11.973 回答
3

不久前我遇到了同样的问题。我的解决方案是放弃该方法的迭代,read即使您的子进程未完成执行等,该方法也会立即返回。

于 2009-04-29T17:24:09.200 回答
2

我使用这个解决方案来获得子进程的实时输出。此循环将在进程完成后立即停止,无需使用 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()
于 2014-01-23T19:14:21.943 回答
2

在这里找到了这个“即插即用”功能。像魅力一样工作!

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)
于 2016-08-03T13:28:47.707 回答
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.")
于 2017-06-22T06:14:41.037 回答
2

这是我一直使用的基本骨架。它使实现超时变得容易,并且能够处理不可避免的挂起过程。

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()
于 2017-12-27T14:11:04.513 回答
1

pexpect与非阻塞 readlines 一起使用将解决此问题。它源于管道被缓冲的事实,因此您的应用程序的输出被管道缓冲,因此在缓冲区填满或进程终止之前您无法获得该输出。

于 2010-07-06T14:09:22.727 回答
1

完整的解决方案:

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()
于 2013-03-08T07:33:30.493 回答
1

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

下面的代码适用于两者

 p = subprocess.Popen(cmd,
                         shell=True,
                         cwd=work_dir,
                         bufsize=1,
                         stdin=subprocess.PIPE,
                         stderr=sys.stderr,
                         stdout=sys.stdout)
于 2020-08-09T04:21:35.467 回答
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()
于 2019-05-26T20:46:08.547 回答
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
于 2020-03-29T06:23:13.663 回答
0
def run_command(command):
process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
while True:
    output = process.stdout.readline()
    if output == '' and process.poll() is not None:
        break
    if output:
        print(output.strip())
rc = process.poll()
return rc
于 2021-07-17T07:40:28.373 回答
0

这对我有用:

import subprocess
import sys

def run_cmd_print_output_to_console_and_log_to_file(cmd, log_file_path):
    make_file_if_not_exist(log_file_path)
    logfile = open(log_file_path, 'w')

    proc=subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell = True)
    for line in proc.stdout:
        sys.stdout.write(line.decode("utf-8") )
        print(line.decode("utf-8").strip(), file=logfile, flush=True)
    proc.wait()

    logfile.close()
于 2022-03-04T19:56:55.170 回答