python - Python 3 将 ping 设置为变量返回 0
问题描述
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()
将其设置为浮点数
[root@web python3]# python3 testNet.py
8.113
0.0
网络错误:没有连接到目的地
添加了另一个 url 并将其设置为 int
[root@web python3]# python3 testNet.py
44.992
0
11.377
0
网络错误:没有连接到目的地
为什么当您尝试对它执行任何操作时 ping 它会将其设置为零?其他印刷品只是为了看看它是如何通过的
解决方案
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"])
推荐阅读
- javascript - 从表单中已更改的字段中获取值和名称
- python - views.py 中未定义 Django 模型
- c# - 如何使用 JSON.NET 检查 JSON 中的缺失字段
- android - 在片段之间共享 EditText 值
- java - 如何打印出二维数组(矩阵)对象
- powershell - 在 Powershell 中比较 TICKS 时间
- php - setter函数中的PHP变量变量
- solaris - Solaris 11 将软件包组从大型服务器减少到最小服务器
- python - 在数据框中的其他列上使用应用函数的新列
- c++ - Visual Studio Code c++ 代码编译,但没有控制台输出