Python 3 将 ping 设置为变量返回 0

标签 python linux python-3.x

import os

host = "www.yahoo.com"
test = os.system("ping -c 10 " + host + " | tail -1| awk '{print $4}' | cut -d '/' -f 2")

print(test)

def check_ping():
    hostname = "www.google.com"

    response = os.system("ping -c 10 " + hostname + " | tail -1| awk '{print $4}' | cut -d '/' -f 2")

    print(int(response))
    if response > 0:
        print("boo")
        print("Network Active. Average response time is: " + str(response))

    else:
        print("Network Error: No connection to destination")
check_ping()

将其设置为 float

[root@web python3]# python3 testNet.py

8.113

0.0

网络错误:未连接到目的地

添加了另一个 url 并将其设置为 int

[root@web python3]# python3 testNet.py

44.992

0

11.377

0

网络错误:未连接到目的地

为什么当你尝试用它做任何事情时,它会将其设置为零? 其他打印只是为了看看它是如何通过的

最佳答案

os.system 将返回进程的值,如果没有错误,则为 0。您需要使用subprocess.check_output从命令中获取stdout

import subprocess

output = subprocess.check_output(["ping -c 10 " + "www.google.com" + " | tail -1| awk '{print $4}' | cut -d '/' -f 2"])

关于Python 3 将 ping 设置为变量返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50507807/

相关文章:

Python。 while 循环中的变量未更新。

c++ - Cevelop——在编译时从环境变量设置 C++ 宏值?

linux - 在开始之前,我如何检查特定服务器是否正在运行(使用 virsh 命令)|重启了吗?

python - Windows 10 更新后无法在 Python3.7 中导入任何内容

python-3.x - 如何在Python中仅打印数据类型

python - 如何检查 raw_input() 是否来自 Python 中的键盘

python - 无法使用Python调用GDB用户定义的函数

python - '~' 在 python 中是什么意思?

linux - 查找文件类型的shell脚本

python - 如何以 UTF-8 编码 WSGI 输出?