1

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()
Grant Foster
  • 722
  • 2
  • 11
  • 21
Jonson
  • 33
  • 5
  • Have you tried this? https://stackoverflow.com/questions/4084322/killing-a-process-created-with-pythons-subprocess-popen – Grant Foster Oct 09 '18 at 20:19
  • `subprocess.check_call()` doesn't return until the process has exited, so there's nothing to terminate. – Barmar Oct 09 '18 at 20:22
  • It also doesn't return the process output, it returns a `CompletedProcess` object. If you want the output, use `check_output()`, not `check_call()`. – Barmar Oct 09 '18 at 20:24
  • If you want to run a subprocess without waiting for it to exit, use `subprocess.Popen()` and then read from the pipe. – Barmar Oct 09 '18 at 20:26
  • you are right about Popen. process = subprocess.Popen(shlex.split("ping -c 10 gogole.com"), stdout=PIPE ) readme = process.stdout.read() if "PING" in readme: print "yes, is there" – Jonson Oct 10 '18 at 18:49

2 Answers2

0

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.

Prune
  • 76,765
  • 14
  • 60
  • 81
0
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
Jonson
  • 33
  • 5