实时子进程.通过stdout和PIPE打开 [英] real time subprocess.Popen via stdout and PIPE

查看:108
本文介绍了实时子进程.通过stdout和PIPE打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从subprocess.Popen通话中获取stdout,尽管我很容易做到这一点:

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

我想实时"获取stdout.使用上述方法,PIPE等待获取所有stdout,然后返回.

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).

有没有一种方法可以在运行时逐行获取stdout?还是这是subprocess的限制(必须等到PIPE关闭).

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).

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

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

推荐答案

您的解释器正在缓冲.在打印语句后,添加对sys.stdout.flush()的调用.

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

这篇关于实时子进程.通过stdout和PIPE打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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