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

Using subprocess to get output of grep piped through head -1

我要做的事情的要点是:

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 模块不是很熟悉,我希望得到有关如何获得此输出以及我目前做错了什么的建议。

让 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

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

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()