我一直在尝试使用子进程模块将python脚本作为子进程运行,并且遇到了一个逐行读取输出的问题。
我读过的文档表明,您应该能够在stdout上使用子进程和调用readline(),如果我调用的脚本是bash脚本,这确实可以工作。但是,当我运行python脚本时,会读取when ()块,直到整个脚本完成为止。
我已经写了几个测试脚本来重复这个问题。在测试脚本中,我将python脚本( tst1.py )作为一个子进程从python脚本(tst.py)中运行,然后逐行读取tst1.py的输出。
tst.py启动tst1.py并尝试逐行读取输出:
#!/usr/bin/env python
import sys, subprocess, multiprocessing, time
cmdStr = 'python ./tst1.py'
print(cmdStr)
cmdList = cmdStr.split()
subProc = subprocess.Popen(cmdList, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
while(1):
# this call blocks until tst1.py has completed, then reads all the output
# it then reads empty lines (seemingly for ever)
ln = subProc.stdout.readline()
if ln:
print(ln)tst1.py简单地循环打印出一条消息:#!/usr/bin/env python import time
if __name__ == "__main__":
x = 0
while(x<20):
print("%d: sleeping ..." % x)
# flushing stdout here fixes the problem
#sys.stdout.flush()
time.sleep(1)
x += 1如果tst1.py被写为shell脚本tst1.sh:
#!/bin/bash
x=0
while [ $x -lt 20 ]
do
echo $x: sleeping ...
sleep 1
let x++
donereadline()的工作方式与预期一致。
经过一番尝试后,我发现这种情况可以通过刷新tst1.py中的stdout来解决,但我不明白为什么需要这样做。我想知道是否有人对这种行为有解释?
我正在运行redhat 4 linux: Linux lb-cbga-05 2.6.9-89。EDT #1 SMP Mon Apr 20 10:33:05 EDT 2009 x86_64 GNU/Linux
发布于 2012-11-14 23:57:55
因为如果输出被缓冲在某个地方,父进程将看不到它,直到子进程存在时,输出才会刷新,所有fd都会关闭。至于为什么它在不显式刷新输出的情况下与bash一起工作,因为当您在大多数shell中输入echo时,它实际上会派生一个执行echo (打印某些内容)的进程,并且存在,所以输出也会被刷新。
https://stackoverflow.com/questions/13382272
复制相似问题