Python Function to test ping(用于测试 ping 的 Python 函数)
问题描述
我正在尝试创建一个函数,我可以定时调用该函数来检查是否有良好的 ping 并返回结果,以便我可以更新屏幕显示.我是 python 新手,所以我不完全了解如何在函数中返回值或设置变量.
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.
这是我的有效代码:
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"
这是我显示 pingstatus
的方式:
And here is how I display pingstatus
:
label = font_status.render("%s" % pingstatus, 1, (0,0,0))
所以我正在寻找的是如何从函数中返回 pingstatus.任何帮助将不胜感激.
So what I am looking for is how to return pingstatus from the function. Any help would be greatly appreciated.
推荐答案
看起来你想要 return
关键字
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
您需要在变量中捕获/接收"函数的返回值(pingstatus),例如:
You need to capture/'receive' the return value of the function(pingstatus) in a variable with something like:
pingstatus = check_ping()
注意:ping -c
适用于 Linux,Windows 使用 ping -n
NOTE: ping -c
is for Linux, for Windows use ping -n
关于python函数的一些信息:
Some info on python functions:
http://www.tutorialspoint.com/python/python_functions.htm
http://www.learnpython.org/en/Functions
可能值得阅读一个很好的 Python 入门教程,它将涵盖所有基础知识.我建议调查 Udacity.com 和 codeacademy.com
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
这篇关于用于测试 ping 的 Python 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于测试 ping 的 Python 函数
基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01