Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get return value from shell command in python

Tags:

python

shell

unix

I'm doing os.system to tail for a live file and grep for a string How can I execute something when the grep succeeds? For example

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

Is there any way I can do this? It will only come to the if block when the os.system statement is completed.

like image 211
hck3r Avatar asked Jun 16 '26 22:06

hck3r


1 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)
like image 106
Blender Avatar answered Jun 19 '26 13:06

Blender