私はPythonでsubprocess
モジュールを使用して標準入力を読み込み、標準出力をストリーミング形式で書き込むプロセスと通信しようとしています。私は、入力を生成するイテレータからサブプロセスを読み込み、サブプロセスから出力行を読みたいと思っています。入力ラインと出力ラインとの間には1対1の対応関係はない。どのように文字列を返す任意のイテレータからサブプロセスをフィードできますか?ここでPythonイテレータからサブプロセスの標準入力をどのように送ることができますか?
は、簡単なテストケースを与えるいくつかのサンプルコード、および何らかの理由で動作しない、私は試してみましたいくつかの方法である:
#!/usr/bin/python
from subprocess import *
# A really big iterator
input_iterator = ("hello %s\n" % x for x in xrange(100000000))
# I thought that stdin could be any iterable, but it actually wants a
# filehandle, so this fails with an error.
subproc = Popen("cat", stdin=input_iterator, stdout=PIPE)
# This works, but it first sends *all* the input at once, then returns
# *all* the output as a string, rather than giving me an iterator over
# the output. This uses up all my memory, because the input is several
# hundred million lines.
subproc = Popen("cat", stdin=PIPE, stdout=PIPE)
output, error = subproc.communicate("".join(input_iterator))
output_lines = output.split("\n")
それでは、どのように私は私のサブプロセスは、ANから読み取ることができますイテレータは行ごとに標準出力から読み込みますが、
子プロセスで 'exit()'を実行すると、 'SystemExit'が呼び出されます。代わりに['os._exit(0)'](https://docs.python.org/2/library/os.html#os._exit)を使うべきです。 – hakanc
['os.fork () '](http://stackoverflow.com/a/32331150/4279)を参照してください。 'os.fork()'の可能性のある問題の例を以下に示します:[標準ライブラリのロックはforkでサニタイズする必要があります](http://bugs.python.org/issue6721) – jfs