我有两个工作命令,用于检查设备是否上传/下移并复制数据包丢失值。
用于上下检查设备我使用
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一次以获得两个结果?
答案 0 :(得分:1)
使用子流程。然后你可以直接解析你需要的字符串。
编辑:更新了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