私は、Pythonでサブプロセスを使用してパイプを連鎖させ、行ごとに(事前に使用せずに)パイプを読み書きするために、次のコードを使用しているように見えますcommunicate()
。このコードは、Unix コマンドを呼び出し ( mycmd
)、その出力を読み取り、それを別の Unix コマンドの stdin に書き込み ( next_cmd
)、最後のコマンドの出力をファイルにリダイレクトするだけです。
# some unix command that uses a pipe: command "a"
# writes to stdout and "b" reads it and writes to stdout
mycmd = "a | b"
mycmd_proc = subprocess.Popen(mycmd, shell=True,
stdin=sys.stdin,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# nextCmd reads from stdin, and I'm passing it mycmd's output
next_cmd = "nextCmd -stdin"
output_file = open(output_filename, "w")
next_proc = subprocess.Popen(next_cmd, shell=True,
stdin=subprocess.PIPE,
stdout=output_file)
for line in iter(mycmd.stdout.readline, ''):
# do something with line
# ...
# write it to next command
next_proc.stdin.write(line)
### If I wanted to call another command here that passes next_proc output
### line by line to another command, would I need
### to call next_proc.communicate() first?
next_proc.communicate()
output_file.close()
これは機能しているように見えcommunicate()
、コマンドの最後でのみ呼び出されます。
このコードを拡張して別のコマンドを追加しようとしているので、次のことができます。
mycmd1 | mycmd2 | mycmd3 > some_file
意味: 行ごとに、Python からmycmd1 の出力を読み取り、行を処理し、それを mycmd2 にフィードし、mycmd2 の出力を読み取り、それを 1 行ずつ処理して mycmd3 にフィードしますsome_file
。これは可能ですか、またはデッドロック/ブロッキング/フラッシュされていないバッファで終了することはありますか? 次のコマンドにフィードする前に、間に Python を介入させ、各コマンドの出力を 1 行ずつ後処理したいので、3 つの UNIX コマンドをパイプとして呼び出すだけではないことに注意してください。
通信を呼び出してすべての出力をメモリにロードすることを避けたい - 代わりに行ごとに解析したい。ありがとう。