Skip to content Skip to sidebar Skip to footer

Using Subprocess To Get Output Of Grep Piped Through Head -1

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 = sub

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

Solution 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

Post a Comment for "Using Subprocess To Get Output Of Grep Piped Through Head -1"