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

use*_*153 4 python grep subprocess pipe head

我想做的要点是:

grep -n "some phrase" {some file path} | head -1
Run Code Online (Sandbox Code Playgroud)

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

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

我收到很多回复说

"grep: writing output: Broken pipe"
Run Code Online (Sandbox Code Playgroud)

我对该模块不太熟悉subprocess,我想了解如何获得此输出以及我目前做错了什么。

Pad*_*ham 5

该文档向您展示了如何使用 Popen替换 shell 管道

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()
Run Code Online (Sandbox Code Playgroud)