用于测试 ping 的 Python 函数

Python Function to test ping(用于测试 ping 的 Python 函数)
本文介绍了用于测试 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 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)