实时 subprocess.Popen 通过 stdout 和 PIPE

发布于 2024-08-18 16:46:30 字数 652 浏览 10 评论 0原文

我正在尝试从 subprocess.Popen 调用中获取 stdout ,尽管我可以通过这样做轻松实现这一点:

cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE)
for line in cmd.stdout.readlines():
    print line

我想在中获取 stdout “即时的”。通过上述方法,PIPE 正在等待获取所有 stdout,然后返回。

因此,出于记录目的,这不符合我的要求(例如“查看”发生的情况)。

有没有办法在运行时逐行获取stdout?或者这是子进程的限制(必须等到 PIPE 关闭)。

编辑 如果我将 readlines() 切换为 readline() ,我只能得到 stdout 的最后一行(不理想):

In [75]: cmd = Popen('ls -l', shell=True, stdout=PIPE)
In [76]: for i in cmd.stdout.readline(): print i
....: 
t
o
t
a
l

1
0
4

I am trying to grab stdout from a subprocess.Popen call and although I am achieving this easily by doing:

cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE)
for line in cmd.stdout.readlines():
    print line

I would like to grab stdout in "real time". With the above method, PIPE is waiting to grab all the stdout and then it returns.

So for logging purposes, this doesn't meet my requirements (e.g. "see" what is going on while it happens).

Is there a way to get line by line, stdout while is running? Or is this a limitation of subprocess(having to wait until the PIPE closes).

EDIT
If I switch readlines() for readline() I only get the last line of the stdout (not ideal):

In [75]: cmd = Popen('ls -l', shell=True, stdout=PIPE)
In [76]: for i in cmd.stdout.readline(): print i
....: 
t
o
t
a
l

1
0
4

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

爱给你人给你 2024-08-25 16:46:30

您的口译员正在缓冲。在 print 语句之后添加对 sys.stdout.flush() 的调用。

Your interpreter is buffering. Add a call to sys.stdout.flush() after your print statement.

孤君无依 2024-08-25 16:46:30

实际上,真正的解决方案是将子进程的标准输出直接重定向到进程的标准输出。

事实上,使用您的解决方案,您只能同时打印 stdout,而不能打印 stderr。

import sys
from subprocess import Popen
Popen("./slow_cmd_output.sh", stdout=sys.stdout, stderr=sys.stderr).communicate()

communicate() 的作用是使调用阻塞,直到子进程结束为止,否则它将直接转到下一行,并且您的程序可能会在子进程之前终止(尽管重定向到标准输出将仍然可以工作,即使你的 python 脚本已经关闭,我测试了它)。

例如,这样您就可以绝对实时地重定向 stdout 和 stderr。

例如,在我的例子中,我使用此脚本 slow_cmd_output.sh 进行了测试:

#!/bin/bash

for i in 1 2 3 4 5 6; do sleep 5 && echo "${i}th output" && echo "err output num ${i}" >&2; done

Actually, the real solution is to directly redirect the stdout of the subprocess to the stdout of your process.

Indeed, with your solution, you can only print stdout, and not stderr, for instance, at the same time.

import sys
from subprocess import Popen
Popen("./slow_cmd_output.sh", stdout=sys.stdout, stderr=sys.stderr).communicate()

The communicate() is so to make the call blocking until the end of the subprocess, else it would directly go to the next line and your program might terminate before the subprocess (although the redirection to your stdout will still work, even after your python script has closed, I tested it).

That way, for instance, you are redirecting both stdout and stderr, and in absolute real time.

For instance, in my case I tested with this script slow_cmd_output.sh:

#!/bin/bash

for i in 1 2 3 4 5 6; do sleep 5 && echo "${i}th output" && echo "err output num ${i}" >&2; done
你在看孤独的风景 2024-08-25 16:46:30

为了“实时”获得输出,subprocess 是不合适的,因为它无法击败其他进程的缓冲策略。这就是为什么我总是建议,每当需要这种“实时”输出抓取时(堆栈溢出是一个很常见的问题!),使用 pexpect(除了 Windows 之外的任何地方 - 在 Windows 上,wexpect< /a>)。

To get output "in real time", subprocess is unsuitable because it can't defeat the other process's buffering strategies. That's the reason I always recommend, whenever such "real time" output grabbing is desired (quite a frequent question on stack overflow!), to use instead pexpect (everywhere but Windows -- on Windows, wexpect).

情深如许 2024-08-25 16:46:30

删除合并输出的 readlines() 。
此外,您还需要强制执行行缓冲,因为大多数命令都会内部缓冲到管道的输出。有关详细信息,请参阅:http://www.pixelbeat.org/programming/stdio_buffering/

Drop the readlines() which is coalescing the output.
Also you'll need to enforce line buffering since most commands will interally buffer output to a pipe. For details see: http://www.pixelbeat.org/programming/stdio_buffering/

何必那么矫情 2024-08-25 16:46:30

因为这是我几天来寻找答案的问题,所以我想把这个问题留给那些关注的人。虽然 subprocess 确实无法对抗其他进程的缓冲策略,但在您使用 subprocess.Popen 调用另一个 Python 脚本的情况下,您可以告诉它启动一个无缓冲的蟒蛇。

command = ["python", "-u", "python_file.py"]
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

for line in iter(p.stdout.readline, ''):
    line = line.replace('\r', '').replace('\n', '')
    print line
    sys.stdout.flush()

我还看到过 popen 参数 bufsize=1universal_newlines=True 有助于暴露隐藏的 stdout 的情况。

As this is a question I searched for an answer to for days, I wanted to leave this here for those who follow. While it is true that subprocess cannot combat the other process's buffering strategy, in the case where you are calling another Python script with subprocess.Popen, you CAN tell it to start an unbuffered python.

command = ["python", "-u", "python_file.py"]
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

for line in iter(p.stdout.readline, ''):
    line = line.replace('\r', '').replace('\n', '')
    print line
    sys.stdout.flush()

I have also seen cases where the popen arguments bufsize=1 and universal_newlines=True have helped with exposing the hidden stdout.

心碎的声音 2024-08-25 16:46:30
cmd = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE)
for line in cmd.stdout:
    print line.rstrip("\n")
cmd = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE)
for line in cmd.stdout:
    print line.rstrip("\n")
舟遥客 2024-08-25 16:46:30

对 readlines 的调用正在等待进程退出。将其替换为围绕 cmd.stdout.readline() 的循环(注意单数),一切都应该很好。

The call to readlines is waiting for the process to exit. Replace this with a loop around cmd.stdout.readline() (note singular) and all should be well.

请止步禁区 2024-08-25 16:46:30

如前所述,当没有终端连接到进程时,问题出在 stdio 库对类似 printf 的语句的缓冲中。无论如何,在 Windows 平台上有一种方法可以解决这个问题。其他平台上也可能有类似的解决方案。

在 Windows 上,您可以在创建进程时强制创建一个新控制台。好处是它可以保持隐藏,所以你永远不会看到它(这是通过子进程模块内的 shell=True 完成的)。

cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE, creationflags=_winapi.CREATE_NEW_CONSOLE, bufsize=1, universal_newlines=True)
for line in cmd.stdout.readlines():
    print line

或者

一个稍微更完整的解决方案是您显式设置 STARTUPINFO 参数,这可以防止启动上面 shell=True 所做的新的和不必要的 cmd.exe shell 进程。

class PopenBackground(subprocess.Popen):
    def __init__(self, *args, **kwargs):

        si = kwargs.get('startupinfo', subprocess.STARTUPINFO())
        si.dwFlags |= _winapi.STARTF_USESHOWWINDOW
        si.wShowWindow = _winapi.SW_HIDE

        kwargs['startupinfo'] = si
        kwargs['creationflags'] = kwargs.get('creationflags', 0) | _winapi.CREATE_NEW_CONSOLE
        kwargs['bufsize'] = 1
        kwargs['universal_newlines'] = True

        super(PopenBackground, self).__init__(*args, **kwargs)

process = PopenBackground(['ls', '-l'], stdout=subprocess.PIPE)
    for line in cmd.stdout.readlines():
        print line

As stated already the issue is in the stdio library's buffering of printf like statements when no terminal is attached to the process. There is a way around this on the Windows platform anyway. There may be a similar solution on other platforms as well.

On Windows you can force create a new console at process creation. The good thing is this can remain hidden so you never see it (this is done by shell=True inside the subprocess module).

cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE, creationflags=_winapi.CREATE_NEW_CONSOLE, bufsize=1, universal_newlines=True)
for line in cmd.stdout.readlines():
    print line

or

A slightly more complete solution is that you explicitly set the STARTUPINFO params which prevents launching a new and unnecessary cmd.exe shell process which shell=True did above.

class PopenBackground(subprocess.Popen):
    def __init__(self, *args, **kwargs):

        si = kwargs.get('startupinfo', subprocess.STARTUPINFO())
        si.dwFlags |= _winapi.STARTF_USESHOWWINDOW
        si.wShowWindow = _winapi.SW_HIDE

        kwargs['startupinfo'] = si
        kwargs['creationflags'] = kwargs.get('creationflags', 0) | _winapi.CREATE_NEW_CONSOLE
        kwargs['bufsize'] = 1
        kwargs['universal_newlines'] = True

        super(PopenBackground, self).__init__(*args, **kwargs)

process = PopenBackground(['ls', '-l'], stdout=subprocess.PIPE)
    for line in cmd.stdout.readlines():
        print line
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文