私はかなり長い実行ジョブを持っています。これは数分間実行されてから再開されます。このタスクは、次のようにキャプチャしたさまざまな情報を出力します。出力をキャプチャして同時にPythonで表示するにはどうしたらいいですか?
output = subprocess.Popen(cmd,stdout=subprocess.PIPE).communicate()
問題は、出力全体を一度に取得することです。プログラムがstdoutに送信している間に出力を表示したいのですが、まだバッファーに戻しています(いくつかの文字列があるかどうか出力を調べる必要があります)。 Rubyでは、私はこのようにそれを行うだろう。このように
from subprocess import Popen, PIPE
p = Popen('grep -ir graph .', stdout=PIPE)
while not p.returncode:
s = p.stdout.readline()
print s
p.poll()
:
cmd = ["./my_program.sh"]
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE) # launch the process
while p.poll() is None: # check if the process is still alive
out = p.stdout.readline() # if it is still alive, grab the output
do_something_with(out) # do what you want with it
バッファサイズを指定していないため、2つのプロセス間に4KBのバッファが追加されるため、通常はブロックされません。 –