3

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.

Joel
  • 4,732
  • 9
  • 39
  • 54
hck3r
  • 189
  • 2
  • 15

2 Answers2

1

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)
Blender
  • 289,723
  • 53
  • 439
  • 496
0
  1. I am not sure that you really need to do this in python - perhaps it would e easier to pipe the tail-f output into awk: https://superuser.com/questions/742238/piping-tail-f-into-awk

  2. If you want to work in python (because you need to do some processing afterwards) then check this link on how to use tail -f: How can I tail a log file in Python?

Community
  • 1
  • 1
ootwch
  • 930
  • 11
  • 32