有很多类似的帖子,但我没有找到答案 .
在Gnu / Linux上,使用 Python
和 subprocess
模块,我使用以下代码迭代使用子进程启动的命令的stdout / sdterr:
class Shell:
"""
run a command and iterate over the stdout/stderr lines
"""
def __init__(self):
pass
def __call__(self,args,cwd='./'):
p = subprocess.Popen(args,
cwd=cwd,
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
)
while True:
line = p.stdout.readline()
self.code = p.poll()
if line == '':
if self.code != None:
break
else:
continue
yield line
#example of use
args = ["./foo"]
shell = Shell()
for line in shell(args):
#do something with line
print line,
这样工作正常......除非执行的命令是 python
,例如`args = ['python','foo.py'],在这种情况下输出不会刷新,而是仅在命令完成时打印 .
有解决方案吗?
1 回答
看看How to flush output of Python print? .
您需要使用-u选项运行python子进程:
或者,如果您可以控制python子流程脚本,则可以使用sys.stdout.flush()在每次打印时刷新输出 .