0

I want to run the following bash command from within my python script

tail input.txt | grep <pattern>

I have written the following lines

bashCommand = "tail input.txt | grep <pattern>'"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)

But this ends up simply printing out the tail of the input file and not the pattern I am trying to grep. How do I circumvent this?

2 Answers 2

1

You can pass shell=True to subprocess.Popen. This will run the command through the shell. If you do this you will need to pass a string instead of an list:

process = subprocess.Popen("tail input.txt | grep ", stdout=subprocess.PIPE, shell=True) print process.communicate()`

You can find a more detailed explanation here: https://unix.stackexchange.com/questions/282839/why-wont-this-bash-command-run-when-called-by-python

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Robbe! Is there a way to make it work with a variable? Where <pattern> can be substituted with a var?
Yes, you can always use string formatting. Or you can use the solution that chepner came up with. His solutions is more robust.
1

Consider implementing the pipe in Python, rather than the shell.

from subprocess import Popen, PIPE
p1 = Popen(["tail", "input.txt"], stdout=PIPE)
process = Popen(["grep", "<pattern>"], stdin=p1.stdout)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.