简体   繁体   中英

python get output of grep -q from subprocess

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM