Pinging in Python with Feedback
Question: so I'm such a noob in Python it's painful but I'm trying to come up with a way
to PING a site, then spit out an 'if/else' clause.

So far I have this:

    
    
    import subprocess 
    command = "ping -c 3 www.google.com"  # the shell command
    process = subprocess.Popen(command, stdout=subprocess.PIPE,     
    stderr=None, shell=True)
    
    #Launch the shell command:
    output = process.communicate()
    
    print output[0]
    

Below is where I go awry, here is part two:

    
    
    if output == 0.00
    print "server is good"
    
    else
    print "server is hosed"
    

Obviously part 2 is not working out.

My question is, how do I "read" the results from the ping (the milliseconds)
icmp_seq=0 ttl=44 time=13.384 ms

and say "if the ping time is faster than 12.000 ms then do THIS" else "do
THAT"

Right now I'm just doing a print but soon I'd like to change that so something
else.


Answer: `subprocess.Popen` is usually not the one you want. There are convenience
functions for all of the simple tasks. In your case, I think you want
`subprocess.check_output`:

    
    
    output = subprocess.check_output(command, shell=True)
    

There are many ways to parse the resulting output string. I am fond of regular
expressions:

    
    
    matches = re.findall(" time=([\d.]+) ms", output)
    

`re.findall` returns a `list` of `str`, but you want to convert that to a
single number so that you can do numerical comparisons. Use the `float()`
constructor to convert the `str`s to `float`s, and then compute the average:

    
    
    matches = [float(match) for match in matches]
    ms = sum(matches)/len(matches)
    

Sample program:

    
    
    import subprocess
    import re
    
    # Run the "ping" command
    command = "ping -c 3 www.google.com"  # the shell command
    output = subprocess.check_output(command, shell=True)
    
    # And interpret the output
    matches = re.findall(" time=([\d.]+) ms", output)
    matches = [float(match) for match in matches]
    ms = sum(matches)/len(matches)
    
    if ms < 12:
         print "Yay"
    else:
         print "Boo"
    

Note that the output of `ping` is not standardized. On my machine, running
Ubuntu 14.04, the above regular expression works. On your machine, running
some other OS, it might need to be different.

