Search code examples
pythongreppopensubprocess

Try to grep with Python subprocess including quote cant find the result


I have one file /tmp/test.txt

this is test
that is test

When I run

[test@localhost]# grep "this is" /tmp/test.txt 
this is test

I got the output.

When I try to run same command with subprocess I didn't get the output. It also return the code 1.

import subprocess
p = subprocess.Popen(['grep', '"this is"', '/tmp/test.txt'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

print p.communicate ()
('', '')

# Command exit code.
print p.poll()
1

I also check the answers Python Subprocess Grep in this and tried shell=True but its not working.

I am missing to place something in subprocess to get the output, but what I dont know :(.


Solution

  • You're searching for the literal pattern "this is", including the quotes. Change the second element in the command list to 'this is' rather than '"this is"'.

    Quoted arguments are only needed when shell=True, in which case the shell interprets them and still passes this is, without quotes, to grep.