Python函数来测试ping [英] Python Function to test ping

查看:178
本文介绍了Python函数来测试ping的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这是我的代码:

  import os 
hostname =google.com
response = os.system(ping -c 1 +主机名)
如果响应== 0:
pingstatus =网络活动
其他:
pingstatus =网络错误



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

  def check_ping():
hostname =google.com
response = os.system(ping -c 1+ hostname)
#然后检查响应...
如果回应== 0:
pingstatus =网络活跃
其他:
pingstatus =网络错误

以下是我如何显示 pingstatus

  label = font_status.render(%s%pingstatus,1,(0,0,0))

所以我在寻找的是如何回复来自函数的pingstatus。任何帮助将不胜感激。

解决方案

它看起来像你想 return 关键字

  def check_ping():
hostname =taylor
response = os.system (ping -c 1+ hostname)
#然后检查响应...
如果响应== 0:
pingstatus =Network Active
else:
pingstatus =网络错误

返回pingstatus

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

  pingstatus = check_ping( )

有关python函数的一些信息:

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



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



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


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.

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:

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.

解决方案

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

You need to capture/'receive' the return value of the function(pingstatus) in a variable with something like:

pingstatus = check_ping()

Some info on python functions:

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

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.com and codeacademy.com

这篇关于Python函数来测试ping的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆