Get return value from shell command in python

I am doing os.system

for a tail for a live file and grep

for a line How can I execute something when grep succeeds? for example

cmd=  os.system(tail -f file.log | grep -i abc)
if (cmd):     
         #Do something and continue tail

      

Is there a way to do this? It will go into the block if

when the os.system instruction is complete.

+3


source to share


2 answers


You can use subprocess.Popen

and read lines from stdout:

import subprocess

def tail(filename):
    process = subprocess.Popen(['tail', '-F', filename], stdout=subprocess.PIPE)

    while True:
        line = process.stdout.readline()

        if not line:
            process.terminate()
            return

        yield line

      



For example:

for line in tail('test.log'):
    if line.startswith('error'):
        print('Error:', line)

      

0


source




0


source







All Articles