あいつの日誌β

あいつの日誌です。

subprocess でコマンドを pipe させる場合

こんな感じ

import subprocess

cmd1 = ('ls', '/tmp')
cmd2 = ('head')
p1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.Popen(cmd2, stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print p2.stdout.readlines()

実行結果

['tmp-xxxxxx\n', 'tmp-yyyyyy\n', 'tmp-zzzzz\n']