msizの日記

ソフトウェア関係の覚え書きが中心になる予定

python + subprocess

昔の「os.system」や「os.popen」の変わりの「subprocess」モジュールを使ったメモ。

  • 「Popen」の引数「stdin, stdout, stderr」に「subprocess.PIPE」を指定すれば、Popen実行結果(Popenオブジェクト)に対して、stdinを通して書き込みができる。
  • Popen実行結果(Popenオブジェクト)に対して「communicate()」でコマンド実行。
  • 個人的には、「Popen」の引数で「shell=True」を指定すると楽。

使用例

>>> import subprocess
>>>
>>> cmd = subprocess.Popen("sed -e 's/1/2/g'", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> cmd.stdin.write("""
... 123
... 456
... 789
... 1a2b3c
... """)
>>> cmd_out = cmd.communicate()
>>> print cmd_out[0]

223
456
789
2a2b3c

>>>

参考にしたページ