2

私はこれを持っていますが、最後にパイプから読み取るサブプロセスがハングします:

$cat waitforinput.sh
#!/bin/sh


while read line
do
echo $line
done                    


>>> p1 = subprocess.Popen(["/home/abc/waitforinput.sh", "-v"], shell=True, executable=None,stdin=subprocess.PIPE, stdout=subprocess.PIPE)
>>> 
>>> 
>>> p1.stdin.write('This is a good idea\n')
>>> p1.stdin.write('This is a good idea\n')
>>> p1.stdin.write('This is a good idea\n')
>>> p1.stdin.write('This is a good idea\n')
>>> p1.stdin.write('This is a good idea\n')
>>> 
>>> 
>>> p1.stdin.flush()
>>> 
>>> for i in p1.stdout:
...     print i 
... 

かからないようにするにはどうしたらいいですか?

4

2 に答える 2

3

flush() の代わりに、 を呼び出しますp1.stdin.close()

...
p1.stdin.write('This is good idea\n')
p1.stdin.write('This is good idea\n')

p1.stdin.close()

for i in p1.stdout:
    print i

アップデート

stdout-iterationwhile-loop with stdout.readline() に置き換えます

Python マンページ-uの一部を参照してください。

stdin、stdout、および stderr を完全にバッファリングしないように強制します。重要なシステムでは、stdin、stdout、および stderr もバイナリ モードにします。xreadlines()、readlines()、およびファイル オブジェクト イテレータ (「sys.stdin の行」) には、このオプションの影響を受けない内部バッファリングがあることに注意してください。これを回避するには、「while 1:」ループ内で「sys.stdin.readline()」を使用します。

p1.stdin.flush()

while True:
    line = p1.stdout.readline()
    if not line:
        break
    print line

出力は得られますが、がないclose()とスクリプトは終了しません。とにかく使うべきclose()です。

于 2013-08-09T18:23:38.767 に答える