Ced
Ced

Reputation: 1539

Python how to make a ping -t script looping indefinitely

I want to run a python script file with this ping -t www.google.com command.

So far I did one with the ping www.google.com command which works, but I didn't suceed to do on with the ping -t looping indefinitely.

You can find below my ping.py script:

import subprocess

my_command="ping www.google.com"
my_process=subprocess.Popen(my_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

result, error = my_process.communicate()
result = result.strip()
error = error.strip()

print ("\nResult of ping command\n")
print("-" *22)
print(result.decode('utf-8'))
print(error.decode('utf-8'))
print("-" *22)
input("Press Enter to finish...")

I want the command box to stay open when finished. I am using Python 3.7.

Upvotes: 1

Views: 327

Answers (1)

Reductio
Reductio

Reputation: 539

If you want to keep the process open and communicate with it all the time, you can use my_process.stdout as input and e.g. iterate over it's lines. With "communicate" you wait until the process completes, which would be bad for an indefinitely running process :)

import subprocess

my_command=["ping", "www.google.com"]
my_process=subprocess.Popen(my_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while True:
    print( my_process.stdout.readline() )

EDIT

In this version we use re to only get the "time=xxms" part from the output:

import subprocess
import re

my_command=["ping", "-t", "www.google.com"]
my_process=subprocess.Popen(my_command, stdout=subprocess.PIPE, 
stderr=subprocess.PIPE)

while True:
    line = my_process.stdout.readline() #read a line - one ping in this case
    line = line.decode("utf-8") #decode the byte literal to string
    line = re.sub("(?s).*?(time=.*ms).*", "\\1", line) #find time=xxms in the string and use only that

    print(line)

Upvotes: 1

Related Questions