0

I want one help regarding subprocess.call in python I have launched one process using subprocess.call and it is saving log in log file. I want to terminate process once specific string is there in log file. I have read many answers and use like process.kill() or process.terminate() but it is not working.

log = open(log_file,"w")

subprocess.call(full_command, stdin=None, stdout=log, stderr=log, shell=False, timeout=None)

When specific string is there in log for example "abc" then I want to terminate the process. Can you please help?

Aakash Patel
  • 111
  • 7

1 Answers1

0

As you are using Linux, you can let grep do the work for you, and if you restrict it to a single match (with -m1) it will also cause the process to exit.

So, using this as a sample process, which works for a few seconds, then prints SUCCESS or FAIL then works for a few more seconds.

#!/bin/bash
for ((i=0;i<3;i++)) ; do
   printf "Working: $i\n"
   sleep 1
done
((r=RANDOM%10))
if [ $r -lt 5 ] ; then
   printf "Success\n"
else
   printf "Fail\n"
fi
for ((i=3;i<9;i++)) ; do
   printf "Working: $i\n"
   sleep 1
done

You should be able to test it in the shell with:

./task | grep -E -m1 'Success|Fail'

If you test that, you should see that it exits as soon as success or failure are output.

If so, that leads to some Python like this:

import subprocess 

sp = subprocess.run("./task | grep -E -m1 'Success|Fail'", shell=True, capture_output=True)

print(sp.stdout)        # prints b'Success\n'
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432