0

I'm turning a bash script into python, but when do this in python:

cmd = r"grep 'name' somefile.log | grep -v 'result=""' | grep -v result='is\ OK'"
results_str = os.system(cmd)
print (results_str,"\n")

I don't get any output of grep. If I run it from the command line/bash, I get

grep 'name' somefile.log | grep -v 'result=""' | grep -v result='is\ OK'
name="blah", result="the thing I'm trying to grep", action="", info=""

What is wrong with my python grep?

oguz ismail
  • 1
  • 16
  • 47
  • 69
batflaps
  • 261
  • 3
  • 12
  • `os.system` doesn't return the value you are expecting: https://stackoverflow.com/a/26005591/11424673 it returns the process exit value, not any standard output – Hymns For Disco Feb 04 '20 at 05:29

1 Answers1

0

Use - os.popen()

os.popen() gives you control over the process's input or output file streams. os.system() doesn't. If you don't need to access the process's I/O, you can use os.system() for simplicity.

So your revised code will be -

cmd = r"grep 'name' somefile.log | grep -v 'result=""' | grep -v result='is\ OK'"
results_str = os.popen(cmd)
print (results_str,"\n")
Chetan Patel
  • 772
  • 4
  • 8