问题描述
我正在尝试创建一个函数,我可以定时调用该函数来检查是否有良好的 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 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!