使用子进程获取通过head -1传输的grep的输出

时间:2015-01-26 16:33:43

标签: python grep pipe subprocess head

我想要做的就是:

grep -n "some phrase" {some file path} | head -1

我想将此输出传递给python。到目前为止我尝试过的是:

p = subprocess.Popen('grep -n "some phrase" {some file path} | head -1',shell=True,stdout=subprocess.PIPE)

我收到很多消息说

"grep: writing output: Broken pipe"

我对subprocess模块不是很熟悉,我想知道如何获得这个输出,以及我目前做错了什么。

2 个答案:

答案 0 :(得分:4)

文档向您展示如何使用Popen replace shell piping

from subprocess import PIPE, Popen


p1 = Popen(['grep', '-n', 'some phrase', '{some file path}'],stdout=PIPE)
p2 = Popen(['head', '-1'], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
out,err = output = p2.communicate()

答案 1 :(得分:0)

让shell为你做(懒惰的解决方法):

import subprocess
p = subprocess.Popen(['-c', 'grep -n "some phrase" {some file path} | head -1'], shell=True, stdout=subprocess.PIPE)
out, err = p.communicate()
print out, err