Skip to content Skip to sidebar Skip to footer

Detecting Internet For A Specific Interface Over Python

I'm looking for a solution to check whether or not a specific interface (eth0, wlan0, etc) has internet or not. My situation is as follows; I have 2 active connections. One etherne

Solution 1:

The text variable prints out the pint command output, it's just the finding the text inside the print command output that's not working.

Yes because you don't capture stderr, you can redirect stderr to stdout, you can also just call communicate to wait for the process to finish and get the output:

p = subprocess.Popen(command, stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)
out,_ = p.communicate()

You can also just use check_call which will raise an error for any non-zero exit status:

from subprocess import check_call, CalledProcessError, PIPE 

defis_reachable(inter, i, add):
    command = ["ping", "-I", inter, "-c", i, add]
    try:
        check_call(command, stdout=PIPE)
        returnTrueexcept CalledProcessError as e:
        print e.message
        returnFalse

If you want to only catch a certain error, you can check the return code.

defis_reachable(inter, i, add):
    command = ["ping", "-I", inter, "-c", i, add]
    try:
        check_call(command, stdout=PIPE)
        returnTrueexcept CalledProcessError as e:
        if e.returncode == 1:
            returnFalseraise

Post a Comment for "Detecting Internet For A Specific Interface Over Python"