我々は持っています:
- Python ベースのサーバー (A)
- (同じ Linux マシン上で) 実行中のコマンドライン アプリケーションは、 を読み取り
stdin
、何かを計算し、出力をstdout
(B)に提供します。
stdin
(A) から(B) に入力を送信し、(B) からの応答を待つ、つまりその を読む最良の (最もエレガントな) 方法は何stdout
ですか?
標準ライブラリの Python のモジュールを使用して (B) を生成すると、(B) のとを (A) によって読み書き可能なバイト バッファとしてsubprocess
設定できます。stdin
stdout
b = Popen(["b.exe"], stdin=PIPE, stdout=PIPE)
b.stdin.write("OHAI\n")
print(b.stdout.readline())
与えられた例では、communicate
デッドロックを回避するように注意するため、使用するのが最も簡単です。
b = Popen(["b.exe"], stdin=PIPE, stdout=PIPE)
b_out = b.communicate("OHAI\n")[0]
print(b_out)
http://docs.python.org/release/3.1.3/library/subprocess.html
http://docs.python.org/release/3.1.3/library/subprocess.html#subprocess.Popen.communicate
双方向通信が多い場合は、バッファがいっぱいになることによるデッドロックを避けるように注意する必要があります。コミュニケーション パターンがこの種の問題を引き起こす場合は、socket
代わりにコミュニケーションの使用を検討する必要があります。
@Deestan が指摘したように、subprocess,module はエレガントで実績のあるものです。Python からコマンドを実行する必要がある場合、サブプロセスをよく使用します。
私たちのものは、主に社内で構築されたコマンドを実行し、その出力をキャプチャすることを含みます。このようなコマンドを実行するラッパーは、このように見えます。
import subprocess
def _run_command( _args, input=[],withShell=False):
"""
Pass args as array, like ['echo', 'hello']
Waits for completion and returns
tuple (returncode, stdout, stderr)
"""
p = subprocess.Popen(_args, shell = withShell,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
[p.stdin.write(v) for v in input]
stdout, stderr = p.communicate()
return p.returncode, stdout, stderr
_,op,er = _run_command(['cat'],["this","is","for","testing"])
value="".join(op)
print value
_,op,er = _run_command(['ls',"/tmp"])
value="".join(op)
print value
Bへの入力が最小限の場合、サブプロセスはyesです。