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

让人想犯罪 __ 提交于 2020-01-04 06:24:04

问题


The gist of what I'm trying to do is this:

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

I would like to pass the output of this into python. What I've tried so far is:

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

I get back a lot of messages saying

"grep: writing output: Broken pipe"

I'm not very familiar with the subprocess module, I would like advice as to how to get this output, and what I am currently doing wrong.


回答1:


The docs show you how to replace shell piping using 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()



回答2:


Let shell do it for you (lazy workaround):

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


来源:https://stackoverflow.com/questions/28154437/using-subprocess-to-get-output-of-grep-piped-through-head-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!