4

I am using the following code to ping a website to check for connectivity. How can I parse the results back to get "Lost = " to see how many were 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 I get from 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
  • 2
    How about if you also post just what string you get from 'out', since you have gone so far as to print it? Commented Feb 21, 2012 at 14:00

3 Answers 3

7

Step 1: Construct a regular expression that will match Lost = 0 (0% loss), using \d tags to substitute for the numeric values, which will vary. Use capturing groups to preserve these values.

Step 2: Use re.search to scan the out string.

Step 3: Extract the values from the re's capturing groups.

Sign up to request clarification or add additional context in comments.

1 Comment

Give a man a regex, and he will parse for a day. Teach a man to regex, and he'll parse for a lifetime! Good answer!
3
lost = out.split('Lost = ')[1].split(',')[0]

If you do this with your example, lost would contain 0 (0% loss)

If you want just the total you can do

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

If you want the percentage you can do

lostPercent = out.split('%')[0].split('(')[1]

Comments

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

This applies a regular expression to capture the number that comes after "Lost =" and converts it to an integer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.