使用Python和正则expression式分析Windows命令结果

我正在使用下面的代码来ping一个网站来检查连接。 我怎样才能把结果parsing成“Lost =”,看看有多less人丢了?

def pingTest(): host = "www.wired.com" ping = subprocess.Popen( ["ping","-n","4",host], stdout = subprocess.PIPE, stderr = subprocess.PIPE ) out,error = ping.communicate() print out 

这是我从外面得到的回报

 Pinging wired.com [173.223.232.42] with 32 bytes of data: Reply from 173.223.232.42: bytes=32 time=54ms TTL=51 Reply from 173.223.232.42: bytes=32 time=54ms TTL=51 Reply from 173.223.232.42: bytes=32 time=54ms TTL=51 Reply from 173.223.232.42: bytes=32 time=54ms TTL=51 Ping statistics for 173.223.232.42: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 54ms, Maximum = 54ms, Average = 54ms 

步骤1:构建一个匹配Lost = 0 (0% loss)的正则表达式,使用\d标签替换数值,这将会变化。 使用捕获组来保存这些值。

第2步:使用re.search来扫描out字符串。

第3步:从re的捕获组中提取值。

 lost = out.split('Lost = ')[1].split(',')[0] 

如果你用你的例子做这个,丢失将包含0(0%损失)

如果你只想要你可以做的总数

 lostTotal = out.split('Lost = ')[1].split(' ')[0] 

如果你想要的百分比,你可以做

 lostPercent = out.split('%')[0].split('(')[1] 
 import re lost = int(re.findall(r"Lost = (\d+)", out)[0]) 

这将应用正则表达式来捕获“Lost =”之后的数字并将其转换为整数。