python中subprocess实施shell命令,怎样做到及时的获取shell命令输出内容

python中subprocess执行shell命令,怎样做到及时的获取shell命令输出内容
我想shell一有输出就能立即获得内容,如果使用subprocess.wait()的话,只能等所有代码都结束以后才能得到输出,且这样的话可能还存在管道被塞满的问题吧?
而下面的代码存在一个问题是,循环永远不会退出,returncode值永远得不到。
求大牛给一个可行的解决方案。

import subprocess
subp=subprocess.Popen('python /tmp/test.py',shell=True,stdout=subprocess.PIPE)
while subp.returncode=None:
    print subp.returncode,subp.stdout.readline()
print subp.returncode


#/tmp/test.py
for i in range(1,10):
    print i

------解决方案--------------------
其实,并不是你想的那样,因为test.py,也不是实时输出,只有在每次输出,清空一下stdout才能看到你想看到的效果。
test.py
import sys
import time
for i in range(1,10):
    print i
    sys.stdout.flush()
    time.sleep(1)


import subprocess
subp=subprocess.Popen('python test.py',shell=True,stdout=subprocess.PIPE)
c=subp.stdout.readline()
while c:
    print c
    c=subp.stdout.readline()

print subp.returncode

这样,你观察很明显,如果你将sys.stdout.flush(),删除,你会发现都是最后一刻才输出,因为print时代缓冲的。


------解决方案--------------------
Popen.poll() 
用于检查子进程是否已经结束。设置并返回returncode属性。
Popen.wait() 
等待子进程结束。设置并返回returncode属性。
不然,不会设置returncode
------解决方案--------------------
可以按你原来的稍改一下while条件:
while subp.poll() == None:
------解决方案--------------------
刚好也有类似的需求,借用一下,3Q~~~python中subprocess实施shell命令,怎样做到及时的获取shell命令输出内容