Reputation: 1055
Recently I spent a few hours to find How can I get output while this script running ping = subprocess.check_output(["start", "cmd.exe", "/k", "ping", "-t", SomeIP], shell=True)
All the answers I've found in the internet proposed to use communicte(), subprocess.call and other unusable commands because all of this command forcing me to stop the script.
Please help me :) My python is 2.7
Upvotes: 1
Views: 1991
Reputation: 571
Another solution is saving the results of the ping to a file then reading from it...
import subprocess, threading
class Ping(object):
def __init__(self, host):
self.host = host
def ping(self):
subprocess.call("ping %s > ping.txt" % self.host, shell = True)
def getping(self):
pingfile = open("ping.txt", "r")
pingresults = pingfile.read()
return pingresults
def main(host):
ping = Ping(host)
ping.ping()
#startthread(ping.ping) if you want to execute code while pinging.
print("Ping is " + ping.getping())
def startthread(method):
threading.Thread(target = method).start()
main("127.0.0.1")
Basically, I just execute the cmd ping command and in the cmd ping command I used the > ping.txt to save the results to a file. Then you just read from the file and you have the ping details. Notice, you can start a thread if you want to execute ping while executing your own code.
Upvotes: 1