我有两个工作命令,检查设备上/下和复制数据包丢失值。
为了检查我用过的设备
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来检查丢包值。我怎么才能平一次才能得到两个结果呢?
发布于 2016-11-25 07:56:58
使用子进程。然后,您可以直接解析所需的字符串。
编辑: 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:", errorhttps://stackoverflow.com/questions/40799978
复制相似问题