Reputation: 955
I have a program running a ping. On my terminal screen i get this:
--- google.com ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 47.963/47.963/47.963/0.000 ms
Connection successful
But on my console i am only getting:
Connection successful
I want my console to show the same ping statistics as my terminal does. I will eventually want to log the ping results onto a txt or csv file, but that will be down the road.
import platform # For getting the operating system name
import subprocess # For executing a shell command
import time
import logging
host = "google.com"
def ping(host):
param = '-n' if platform.system().lower()=='windows' else '-c'
command = ['ping', param, '1', host]
return subprocess.call(command) == 0
while ping(host) == False:
print("There is no network connection")
time.sleep(1)
while ping(host) == True:
print("Connection successful")
time.sleep(1)
How do i get my Terminal Ping statistics to display on my console output?
Upvotes: 1
Views: 1306
Reputation: 95
I re-edited for Linux to ping 3 times and output to a file. This will effectively tell you if the host is up or down. It should still print to terminal, you can use os.system('pause') though I don't remember if that works in Linux.
import os
def main():
f=['8.8.8.8','yahoo.com']
for ips in f:
response = os.system("ping -c3" + ips)
if response == 0:
writeToOut(ips,"host is up")
else:
writeToOut(ips, "host is down")
def writeToOut(ip,result):
f=open('C:/Users/user/Desktop/hostsResults.txt','a')
ip = ip.rstrip()
f.write(ip + "," + result + '\n')
f.close()
main()
Upvotes: 0
Reputation: 3483
To log the full output of the command, use Popen
.
import platform # For getting the operating system name
import subprocess # For executing a shell command
import time
host = "google.com"
def ping(host):
param = '-n' if platform.system().lower()=='windows' else '-c'
command = ['ping', param, '1', host]
return subprocess.Popen(command, stdout=subprocess.PIPE).stdout.read()
while True:
output = ping(host)
print(output)
time.sleep(1)
I tested on Ubuntu with Python 3.6.7
Upvotes: 3