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.
source to share
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)
source to share
-
I'm not sure if you really need to do this in python - it might be easier to pipe the output
tail-f
to awk: https://superuser.com/questions/742238/piping-tail-f-into-awk -
If you want to work in python (because you have to do some processing after that) then check this usage link
tail -f
: How can I log file in Python?
source to share