Parsing Window Processing Results with Python and regex

I use the following code to check the website to check connectivity. How can I analyze the results to get "Lost =" to see how much was lost?

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 

This is the return that I get 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 
+4
source share
3 answers

Step 1: create a regex that matches Lost = 0 (0% loss) using the \d tags to replace the numerical values ​​that will be different. Use capture groups to save these values.

Step 2. Use re.search to scan the out line.

Step 3: Retrieve the values ​​from the re-capture groups.

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

If you do this in your example, the loss will contain 0 (0% loss)

If you want only what you can do

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

If you want a percentage you can make

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

This applies to the regular expression to fix the number that comes after "Lost =" and convert it to an integer.

0
source

Source: https://habr.com/ru/post/1397615/


All Articles