Issue
I'm trying to run greq -q in python, but it does not work.
First I figured out i need to .decode()
the string.
But then I noticed I get empty output everytime even if the grep command does match.
Code:
from subprocess import Popen, PIPE
import os
process1 = Popen("grep -q string file.txt",shell=True,stdout=PIPE)
stdout1,stderr1 = process1.communicate()
if stdout1.decode() == "":
print("not found")
else:
print("found")
What am I doing wrong?
Solution
I dont think you need to look at stdout & stderr.
All you need to do is to look at the return code:
process1 = Popen("grep -q string file.txt",shell=True,stdout=PIPE)
process1.communicate()
print(f"grep returned {process1.returncode}")
grep will return zero when something is found.
Answered By - balderman