Python Function to test ping

153,008

Solution 1

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

EDIT: This is an old question now, but.. for people who have issues with pingstatus not being defined, or returning an unexpected value, first make triple sure your code is right. Then try defining pingstatus before the if block. This may help, but issues arising from this change are for a different question. All the best.

Solution 2

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

Solution 3

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)

Solution 4

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

Solution 5

import platform
import subprocess

def myping(host):
parameter = '-n' if platform.system().lower()=='windows' else '-c'

command = ['ping', parameter, '1', host]
response = subprocess.call(command)

if response == 0:
    return True
else:
    return False
    
print(myping("www.google.com"))
Share:
153,008
user72055
Author by

user72055

Updated on November 24, 2021

Comments

  • user72055
    user72055 over 2 years

    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.

  • user72055
    user72055 over 9 years
    With this code I get "NameError: name 'pingstatus' is not defined"
  • poke
    poke over 9 years
    @user72055 While check_ping now returns a result, you still need to capture that result by assigning it to a variable before you can access the value: pingstatus = check_ping().
  • Timothy C. Quinn
    Timothy C. Quinn almost 7 years
    I've added your ideas to my answer and gave you an upvoat for the good idea.
  • Stevoisiak
    Stevoisiak almost 5 years
    This does not work on Windows. See ePi272314 or Pikamander2's answer for a multi-platform solution.
  • Shtefan
    Shtefan almost 4 years
    The code has an error. pingstatus has to be declared before the if block. Put this line there: pingstatus = None
  • Totem
    Totem over 3 years
    @Shtefan Sorry, this is incorrect. Check this out: stackoverflow.com/questions/58872704/…
  • Shtefan
    Shtefan over 3 years
    @Totem What is incorrect? The variable "pingstatus" is not visible outside of the "if" block. How it can be used for the "return" statement? Have you tried the code before saying "it is incorrect"?
  • Totem
    Totem over 3 years
    @Shtefan Hi. Yes, I checked the code, both as a standalone script, and within ipython interpreter. Both cases it works fine. While I don't see anything wrong necessarily in declaring 'pingstatus' before entering the if block, it also doesn't appear to be necessary. So, in my tests, in both cases, 'pingstatus' is visible outside the if block. Did you read the link I posted, it explains that variables assigned inside an if or while, are scoped to the function, class or module, which appears to be the case here.
  • betontalpfa
    betontalpfa about 3 years
    subprocess.check_output(["ping", "-n" if platform.system().lower()=="windows" else "-c", "1", host])
  • Kurt
    Kurt about 3 years
    Python needs indentation to work correctly and this post appears to have lost its indentation.
  • PssstZzz
    PssstZzz about 2 years
    This isn't working, even on Windows with "ping -n 1 host" it always returns 0.
  • Totem
    Totem about 2 years
    @PssstZzz Pls check that your code is right. pingstatus should not return 0 under any circumstance. I added an edit to my answer you might take a look at.