I\'m trying to create a function that I can call on a timed basis to check for good ping and return the result so I can update the on-screen display. I am new to python so I
Adding on to the other answers, you can check the OS and decide whether to use "-c" or "-n":
import os, platform
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if platform.system().lower()=="windows" else "-c 1 ") + host)
This will work on Windows, OS X, and Linux
You can also use sys
:
import os, sys
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if sys.platform().lower()=="win32" else "-c 1 ") + host)
It looks like you want the return
keyword
def check_ping():
hostname = "taylor"
response = os.system("ping -c 1 " + hostname)
# and then check the response...
if response == 0:
pingstatus = "Network Active"
else:
pingstatus = "Network Error"
return pingstatus
You need to capture/'receive' the return value of the function(pingstatus) in a variable with something like:
pingstatus = check_ping()
NOTE: ping -c
is for Linux, for Windows use ping -n
Some info on python functions:
http://www.tutorialspoint.com/python/python_functions.htm
http://www.learnpython.org/en/Functions
It's probably worth going through a good introductory tutorial to Python, which will cover all the fundamentals. I recommend investigating Udacity.com and codeacademy.com
This is my version of check ping function. May be if well be usefull for someone:
def check_ping(host):
if platform.system().lower() == "windows":
response = os.system("ping -n 1 -w 500 " + host + " > nul")
if response == 0:
return "alive"
else:
return "not alive"
else:
response = os.system("ping -c 1 -W 0.5" + host + "> /dev/null")
if response == 1:
return "alive"
else:
return "not alive"
Try this
def ping(server='example.com', count=1, wait_sec=1):
"""
:rtype: dict or None
"""
cmd = "ping -c {} -W {} {}".format(count, wait_sec, server).split(' ')
try:
output = subprocess.check_output(cmd).decode().strip()
lines = output.split("\n")
total = lines[-2].split(',')[3].split()[1]
loss = lines[-2].split(',')[2].split()[0]
timing = lines[-1].split()[3].split('/')
return {
'type': 'rtt',
'min': timing[0],
'avg': timing[1],
'max': timing[2],
'mdev': timing[3],
'total': total,
'loss': loss,
}
except Exception as e:
print(e)
return None
Here is a simplified function that returns a boolean and has no output pushed to stdout:
import subprocess, platform
def pingOk(sHost):
try:
output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)
except Exception, e:
return False
return True