Python函数来测试ping

时间:2014-10-20 14:53:43

标签: python function variables return

我正在尝试创建一个函数,我可以在定时的基础上调用以检查良好的ping并返回结果,以便我可以更新屏幕显示。我是python的新手,所以我不完全理解如何在函数中返回值或设置变量。

这是我的代码:

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

这是我尝试创建一个函数:

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"

以下是我展示pingstatus

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

所以我要找的是如何从函数返回pingstatus。任何帮助将不胜感激。

6 个答案:

答案 0 :(得分:23)

您似乎想要return关键字

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

您需要捕获/接收'函数(pingstatus)在一个变量中的返回值,如:

pingstatus = check_ping()

有关python函数的一些信息:

http://www.tutorialspoint.com/python/python_functions.htm

http://www.learnpython.org/en/Functions

可能值得通过Python的一个很好的入门教程,它将涵盖所有的基础知识。我建议调查Udacity.comcodeacademy.com

答案 1 :(得分:11)

这是一个简化的函数,它返回一个布尔值,没有输出到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

答案 2 :(得分:9)

再加上这两个答案,您可以检查操作系统并决定是否使用" -c"或" -n":

import os, platform
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if  platform.system().lower()=="windows" else "-c 1 ") + host)

这适用于Windows,OS X和Linux

您还可以使用sys

import os, sys
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if  sys.platform().lower()=="win32" else "-c 1 ") + host)

答案 3 :(得分:1)

试试这个

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

答案 4 :(得分:0)

此函数将测试给定重试次数的 ping,如果可达,则返回 True,否则返回 False -

def ping(host, retry_packets):
    """Returns True if host (str) responds to a ping request."""

    # Option for the number of packets as a function of
    param = '-n' if platform.system().lower() == 'windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, str(retry_packets), host]
    return subprocess.call(command) == 0

# Driver Code
print("Ping Status : {}".format(ping(host="xx.xx.xx.xx", retry_packets=2)))
<块引用>

输出:

Pinging xx.xx.xx.xx with 32 bytes of data:
Reply from xx.xx.xx.xx: bytes=32 time=517ms TTL=60
Reply from xx.xx.xx.xx: bytes=32 time=490ms TTL=60

Ping statistics for xx.xx.xx.xx:
     Packets: Sent = 2, Received = 2, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
     Minimum = 490ms, Maximum = 517ms, Average = 503ms
Ping Status : True

注意:用您的 IP 更改 xx.xx.xx.xx

答案 5 :(得分:-1)

这是我的检查ping功能版本。可能对某人有用:

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"