从 ping 中提取丢包数据导致 python
Extracting packet loss data from ping result in python
我正在尝试从 ping 统计信息中获取 packetloss 数据。到目前为止,我有一大块 ping 统计数据。我只需要丢包数据才能在我的 python 代码中执行 if packetloss < 10%: do something
。这是我的代码:
import subprocess
from subprocess import Popen, PIPE
hostname = "8.8.8.8"
process = subprocess.Popen(['ping','-c','5',hostname],
stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print(stdout)
示例数据:
$ ping -c 5 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: icmp_seq=0 ttl=59 time=7.250 ms
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2
64 bytes from 8.8.8.8: icmp_seq=3 ttl=59 time=19.661 ms
--- 8.8.8.8 ping statistics ---
5 packets transmitted, 2 packets received, 60.0% packet loss
round-trip min/avg/max/stddev = 7.250/13.456/19.661/6.205 ms
尝试以下操作:
packetloss = float([x for x in stdout.decode('utf-8').split('\n') if x.find('packet loss') != -1][0].split('%')[0].split(' ')[-1])
if loss < 10.0:
print("Loss is %s percent" % packetloss)
我正在尝试从 ping 统计信息中获取 packetloss 数据。到目前为止,我有一大块 ping 统计数据。我只需要丢包数据才能在我的 python 代码中执行 if packetloss < 10%: do something
。这是我的代码:
import subprocess
from subprocess import Popen, PIPE
hostname = "8.8.8.8"
process = subprocess.Popen(['ping','-c','5',hostname],
stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print(stdout)
示例数据:
$ ping -c 5 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: icmp_seq=0 ttl=59 time=7.250 ms
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2
64 bytes from 8.8.8.8: icmp_seq=3 ttl=59 time=19.661 ms
--- 8.8.8.8 ping statistics ---
5 packets transmitted, 2 packets received, 60.0% packet loss
round-trip min/avg/max/stddev = 7.250/13.456/19.661/6.205 ms
尝试以下操作:
packetloss = float([x for x in stdout.decode('utf-8').split('\n') if x.find('packet loss') != -1][0].split('%')[0].split(' ')[-1])
if loss < 10.0:
print("Loss is %s percent" % packetloss)