使用子进程获取实时输出 [英] Getting realtime output using subprocess

查看:72
本文介绍了使用子进程获取实时输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation. This requires me to be able to see each line of output from the wrapped program as soon as it is output.

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

I figured that I'd just execute the program using subprocess.Popen, use stdout=PIPE, then read each line as it came in and act on it accordingly. However, when I ran the following code, the output appeared to be buffered somewhere, causing it to appear in two chunks, lines 1 through 332, then 333 through 439 (the last line of output)

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', '')

稍微查看了关于子进程的文档后,我发现了 Popenbufsize 参数,所以我尝试将 bufsize 设置为 1(缓冲每一行)和 0(没有缓冲区),但两个值似乎都没有改变线路的传送方式.

After looking at the documentation on subprocess a little, I discovered the bufsize parameter to Popen, so I tried setting bufsize to 1 (buffer each line) and 0 (no buffer), but neither value seemed to change the way the lines were being delivered.

此时我开始抓紧了,所以我写了下面的输出循环:

At this point I was starting to grasp for straws, so I wrote the following output loop:

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

但得到了相同的结果.

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

Is it possible to get 'realtime' program output of a program executed using subprocess? Is there some other option in Python that is forward-compatible (not exec*)?

推荐答案

我试过了,由于某些原因而代码

I tried this, and for some reason while the code

for line in p.stdout:
  ...

积极缓冲,变种

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

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

does not. Apparently this is a known bug: http://bugs.python.org/issue3907 (The issue is now "Closed" as of Aug 29, 2018)

这篇关于使用子进程获取实时输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆