我正在尝试创建一个函数,我可以定时调用它来检查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。任何帮助都将不胜感激。
发布于 2015-12-25 01:14:12
下面是一个简化的函数,它返回一个布尔值,不会将输出推送到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
发布于 2016-09-19 07:42:00
再加上其他答案,你可以检查操作系统并决定是使用"-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)
发布于 2018-06-14 09:05:22
尝尝这个
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
https://stackoverflow.com/questions/26468640
复制相似问题