Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Function to test ping

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 don't fully understand how to return a value or set a variable in a function.

Here is my code that works:

import os hostname = "google.com" response = os.system("ping -c 1 " + hostname) if response == 0:     pingstatus = "Network Active" else:     pingstatus = "Network Error" 

Here is my attempt at creating a function:

def check_ping():     hostname = "google.com"     response = os.system("ping -c 1 " + hostname)     # and then check the response...     if response == 0:         pingstatus = "Network Active"     else:         pingstatus = "Network Error" 

And here is how I display pingstatus:

label = font_status.render("%s" % pingstatus, 1, (0,0,0)) 

So what I am looking for is how to return pingstatus from the function. Any help would be greatly appreciated.

like image 752
user72055 Avatar asked Oct 20 '14 14:10

user72055


People also ask

How can Python be used to ping a target computer?

You can use the ping function to ping a target. If you want to see the output immediately, emulating what happens on the terminal, use the verbose flag as below. This will yeld the following result. Regardless of the verbose mode, the ping function will always return a ResponseList object.


2 Answers

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

like image 186
Totem Avatar answered Oct 04 '22 17:10

Totem


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 
like image 20
Timothy C. Quinn Avatar answered Oct 04 '22 18:10

Timothy C. Quinn