0

I'm trying to develop a script where a ping command hits 100ms it stops. Is there an easy way to do this?

It would be something like:

import subprocess

command = ['ping', '-c', '4', '8.8.8.8']
proc = subprocess.run(command)
if time > 100:
   break
Lucas Fernandes
  • 1,360
  • 2
  • 8
  • 12
  • Have you tried putting it in a loop? – Sylvester Kruin Feb 24 '22 at 22:32
  • @SylvesterKruin i need to "break" the ping when my terminal shows 100 ms – Lucas Fernandes Feb 24 '22 at 22:33
  • 2
    Ah, so the question is more along the lines of "how do I get the output of `ping`"? – Sylvester Kruin Feb 24 '22 at 22:35
  • It looks like a similar question has been asked before a long time ago, and some of the answers may be outdated, but some should sitll apply to newer versions of Python: [Using module 'subprocess' with timeout](/q/1191374/4518341) – wjandrea Feb 24 '22 at 22:37
  • 1
    "i need to "parse" the ping code" Then you need to capture the output, as it is generated. Please see the linked duplicates and feel free to ask a more specific question if you get stuck again. – Karl Knechtel Feb 24 '22 at 22:56
  • If you need to check whether the process has output recently, but not hang while waiting for the next output (e.g. stop waiting for a ping if it takes too long), then you want a *non-blocking* read of the data piped from the process. See https://stackoverflow.com/questions/375427/a-non-blocking-read-on-a-subprocess-pipe-in-python . – Karl Knechtel Feb 24 '22 at 23:05

1 Answers1

0

Depending on your version of Python, it looks like subprocess.run() has a timeout (measured in seconds) keyword argument that does what you are looking for:

proc = subprocess.run(command, timeout=0.1)

The timeout argument is passed to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated.

elethan
  • 16,408
  • 8
  • 64
  • 87
  • if i use subprocess timeout, i will be restrict to timeout, if i need to do other thing like (if ttl not is 117, do other thing) i need to "parse" the ping code – Lucas Fernandes Feb 24 '22 at 22:44