Terminate a subprocess if string is in output

1k Views Asked by At

I'm trying to terminate a subprocess pid if a string is in the output, but it is not working. What is wrong?

import subprocess
import shlex


if "PING" in subprocess.check_call(shlex.split("ping -c 10 gogole.com")):
    subprocess.check_call(shlex.split("ping -c 10 gogole.com")).terminate()
2

There are 2 best solutions below

0
On

Please refere to the documentation for the methods you call. First of all, check_call executes until the process is finished, then returns the return code from the process. I'm not sure how you intend to find "PING" from a return code, which is typically an integer.

If it is there, look at the body of your if statement: you fork a totally new instance of ping, wait for it to complete, and then try to terminate the return code.

I recommend that you work through a tutorial on subprocesses. Learn how to grab a process handle and invoke operations on that. You'll need to get a handle on the output stream, look for "PING" in that, and then call terminate on the process handle you got at invocation.

0
On
import subprocess, os
run = "ping -c 10 google.com"
log = ""
process = subprocess.Popen(run, stdout=subprocess.PIPE, shell=True)
while True:
    out = process.stdout.read(1)
    log +=out
    print log
    if out == '' and process.poll() != None:
        break
    if "PING" in log:
        print "terminated!"
        process.kill()
        process.terminate()
        break