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 >>>
参考にしたページ
- Python subprocess - karasuyamatenguの日記
- ここの例では、コマンドはリストで渡していることに注意。
- subprocess – プロセスを生成して連携する - Python Module of the Week
- subprocess.Popenにコマンドを文字列で渡して、「shell=True」を渡す例がある。
- pymotwがあると、使い方調べる時にかなり楽ですね。