[英]how to get the normal print statement execution when using stdout=subprocess.PIPE during subprocess call in python
我通过以下命令在python中启动subprocess
:
result = subprocess.Popen([sys.executable, "/subscript.py"] + parameter,stdout=subprocess.PIPE )
result.wait()
out, err = result.communicate()
for line in out.splitlines():
print line
我用这种方法面临的问题是subscript.py
中的所有print
语句都被缓冲到最后,并在执行结束时打印在terminal
上。 因此,如果我的subscript.py
执行大约需要15分钟,那么在15分钟内, terminal
不会显示任何内容,而一旦subscript.py
执行结束,则所有打印语句将一起打印。 我知道这是因为使用了stdout=subprocess.PIPE
,如果我删除它,那么我将得到想要的东西,但是我无法删除它,因为我正在使用它从subscript.py
获取变量的值(我我先在subscript.py
打印该变量,然后在父脚本中进行打印,以获取具有变量值的打印)。
因此,我想要的是应该在subscript.py
中遇到时打印所有打印语句,直到执行结束subscript.py
进行任何缓冲。 有没有办法做到这一点?
更新:我尝试遵循JF Sebastian的方法,但仍然得到相同的输出。 来自子流程的打印内容被缓冲,一旦子流程结束,就将它们打印到终端。 我拥有的更新代码是:
result = subprocess.Popen([sys.executable, "/subscript.py"] + parameter,stdout=subprocess.PIPE,bufsize=1)
with result.stdout:
for line in iter(result.stdout.readline, b''):
print line,
result.wait()
您链接的答案仅在标准输出缓冲区在子对象中刷新后才打印任何内容, 因为答案本身已明确指出。
使用-u
参数 ,在Python子进程中取消缓冲stdout:
#!/usr/bin/env python2
import sys
from subprocess import Popen, PIPE
result = Popen([sys.executable, '-u', '/path/to/subscript.py'] + parameters,
stdout=PIPE, bufsize=1)
with result.stdout:
for line in iter(result.stdout.readline, b''):
print line,
result.wait()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.