目标:ping -c 10000 -i 0.01 -s 50 8.8.8.8 输出第10%快的时间
# -*- coding: utf-8 -*-
import subprocess
import re
# 数组存储返回结果
ping_results = []
def get_ping_result(count, interval, size, ip):
# 构造ping命令
command = 'ping -c %s' % count + " -i %s" % interval + " -s %s" % size + " %s" % ip
p = subprocess.Popen([command],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE, shell = True)
out = p.stdout.read().decode('utf-8')
#提取返回值
regex = r'time=(.+?)ms'
ping_results = re.findall(regex, out)
#排序
ping_results.sort()
#检查下标
index = int(0.1*int(count))
if len(ping_results) == 0:
print("Error! No data!")
elif len(ping_results) < index :
print("Error! Index out of range!")
else:
print(ping_results[index])
if __name__ == '__main__':
get_ping_result('10000', '0.01', '50', '8.8.8.8')
网友评论