python - 在 Linux 中结合两个 ping 命令

标签 python linux terminal

我有两个工作命令,检查设备启动/关闭和复制数据包丢失值。

为了检查我使用的设备上下

 result = os.system ("ping -c 5 " +hostname)

为了复制丢包值,我使用了

packetloss = os.popen ("ping -c 5 " +hostname+ "| grep -oP '\d+(?=% packet loss)'").read().rstrip()
packetloss = int(packetloss)

我知道使用 os.system 不切实际。我的问题是如何结合这两个命令?现在我需要 ping 两次才能启动/关闭设备,然后再 ping 一次以检查数据包丢失值。我怎样才能只 ping 一次以获得两个结果?

最佳答案

使用子进程。然后就可以直接解析你需要的字符串了。

编辑: python 脚本已更新。

import subprocess

output = ""
error = ""
hostname = "www.google.com"
try:
    cmd = "ping -c 5 " + hostname
    p = subprocess.Popen([cmd], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
    output = str(p[0])
    error = str(p[1])
except Exception, e:
    error = str(e)

if output:
    data = output.split("--- " + hostname + " ping statistics ---")
    print "\nPing output:\n", data[0].strip() 
    statistics = data[-1].strip()
    print "\nStatistics:\n", statistics
    packetloss = str(statistics.splitlines()[0]).split(",")
    packetloss = packetloss[2].strip()
    packetloss = packetloss[:packetloss.find("%")]
    print "\nPacketLoss:", packetloss
if error:
    print "\nError:", error

关于python - 在 Linux 中结合两个 ping 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40799978/

相关文章:

linux - Bash 条件表达式 : `-o` . 是什么意思?

c++ - 如何在 C++ 中执行 SQLite 语句

terminal - QEMU 意外退出,退出代码为 -1,stderr : qemu-system-x86_64: Unknown Error

linux - 在提示中包含字符 UTF-8

python - 将键对值插入嵌套字典中,而不在键分隔符后覆盖,从而产生重复键

python - 将 MATLAB 函数转换为 python

python - Unicode解码错误: 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte

linux - 出现错误 : implicit declaration of function 'proc_create'

c - 哈佛 CS50 库,需要在 Mac OS X 上安装帮助

python - 如何调整行或列中的具体数据?