Makistos
2/1/2017 - 2:21 PM

Run commands in shell with error handling. #python #subprocess

Run commands in shell with error handling. #python #subprocess

#!/usr/bin/python

def tryUrl(url):
    try:
        # check_output returns output from command so it could be printed here
        subprocess.check_output('ping ' + url, shell=True)
        return 1
    except subprocess.CalledProcessError, e:
        print 'Connection failed, error: %s' % e.output
        return 0

def connectivityTestWithFail():
    required  = 6
    attempts = 5
    urls = ['http://www.google.com', 'http://www.amazon.com']
    working = 0
    for url in urls * attempts:
        working += tryUrl(url)
        if working >= required:
            break
    print str(working) + "\n"

#connectivityTestWithFail()