次のようにすると:
import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
次のような結果になります:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
どうやら cStringIO.StringIO オブジェクトは、subprocess.Popen に適合するほどファイル ダックに近くないようです。これを回避するにはどうすればよいですか?
ベストアンサー1
Popen.communicate()
ドキュメンテーション:
プロセスの stdin にデータを送信する場合は、stdin=PIPE で Popen オブジェクトを作成する必要があることに注意してください。同様に、結果タプルで None 以外の値を取得するには、stdout=PIPE および/または stderr=PIPE も指定する必要があります。
os.popen* の置き換え
pipe = os.popen(cmd, 'w', bufsize)
# ==>
pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
警告他の OS パイプ バッファーがいっぱいになって子プロセスをブロックすることによるデッドロックを回避するには、stdin.write()、stdout.read()、または stderr.read() ではなく、communicate() を使用してください。
したがって、例は次のように記述できます。
from subprocess import Popen, PIPE, STDOUT
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]
print(grep_stdout.decode())
# -> four
# -> five
# ->
Python 3.5以降(3.6以降encoding
)では、subprocess.run
、入力を文字列として外部コマンドに渡し、その終了ステータスと出力を 1 回の呼び出しで文字列として返します。
#!/usr/bin/env python3
from subprocess import run, PIPE
p = run(['grep', 'f'], stdout=PIPE,
input='one\ntwo\nthree\nfour\nfive\nsix\n', encoding='ascii')
print(p.returncode)
# -> 0
print(p.stdout)
# -> four
# -> five
# ->