1

以下の私の python スクリプトのスニペットでは、temp2 は temp の実行が完了するのを待たず、出力が大きくなる可能性がありますが、単なるテキストです。これにより、temp から結果 ('out') が切り捨てられ、行の途中で停止します。temp からの「out」は、temp 2 が追加されるまで正常に機能します。time.wait() と subprocess.Popen.wait(temp) を追加してみました。これらは両方とも、「out」が切り捨てられないように temp を最後まで実行できるようにしますが、「out2」がないように連鎖プロセスを中断します。何か案は?

temp = subprocess.Popen(call, stdout=subprocess.PIPE)
#time.wait(1)
#subprocess.Popen.wait(temp)
temp2 =  subprocess.Popen(call2, stdin=temp.stdout, stdout=subprocess.PIPE)
out, err = temp.communicate()
out2, err2 = temp2.communicate()
4

2 に答える 2

0

Python Docsによると、communicate() は入力として送信されるストリームを受け入れることができます。を変更stdintemp2てcommunicate() にsubprocess.PIPE入れるoutと、データは適切にパイプ処理されます。

#!/usr/bin/env python
import subprocess
import time

call = ["echo", "hello\nworld"]
call2 = ["grep", "w"]

temp = subprocess.Popen(call, stdout=subprocess.PIPE)

temp2 =  subprocess.Popen(call2, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = temp.communicate()
out2, err2 = temp2.communicate(out)

print("Out:  {0!r}, Err:  {1!r}".format(out, err))
# Out:  b'hello\nworld\n', Err:  None
print("Out2: {0!r}, Err2: {1!r}".format(out2, err2))
# Out2: b'world\n', Err2: None
于 2013-04-30T04:15:53.747 に答える