用于测试 ping 的 Python 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26468640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Function to test ping
提问by user72055
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.
我正在尝试创建一个函数,我可以定时调用它来检查 ping 是否正常并返回结果,以便我可以更新屏幕显示。我是 python 的新手,所以我不完全理解如何在函数中返回一个值或设置一个变量。
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:
这是我的显示方式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.
所以我正在寻找的是如何从函数中返回 pingstatus。任何帮助将不胜感激。
采纳答案by Totem
It looks like you want the returnkeyword
看起来你想要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
You need to capture/'receive' the return value of the function(pingstatus) in a variable with something like:
您需要在一个变量中捕获/“接收”函数(pingstatus)的返回值,例如:
pingstatus = check_ping()
NOTE: ping -cis for Linux, for Windows use ping -n
注意:ping -c适用于 Linux,适用于 Windowsping -n
Some info on python functions:
关于python函数的一些信息:
http://www.tutorialspoint.com/python/python_functions.htm
http://www.tutorialspoint.com/python/python_functions.htm
http://www.learnpython.org/en/Functions
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.comand codeacademy.com
阅读一本很好的 Python 入门教程可能是值得的,该教程将涵盖所有基础知识。我建议调查Udacity.com和codeacademy.com
回答by Timothy C. Quinn
Here is a simplified function that returns a boolean and has no output pushed to stdout:
这是一个简化的函数,它返回一个布尔值并且没有推送到 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
回答by Pikamander2
Adding on to these two answers, you can check the OS and decide whether to use "-c" or "-n":
添加这两个答案,您可以检查操作系统并决定是使用“-c”还是“-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
这将适用于 Windows、OS X 和 Linux
You can also use sys:
您还可以使用sys:
import os, sys
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if sys.platform().lower()=="win32" else "-c 1 ") + host)
回答by sunapi386
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
回答by Валентин
This is my version of check ping function. May be if well be usefull for someone:
这是我的检查 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"

