Well... Am I Online Yet?



How To Check For Internet Connection Using Python

Just a quickie! I find this rather handy so I thought I'd share it. If we can get through to goGgle the response should be 200.

from requests import get
from requests.exceptions import ConnectionError

def is_online(timeout):
    try:
        r = get("https://google.com", timeout=timeout).status_code
    except ConnectionError:
        r = None
    if r == 200:
        return True
    else:
        return False

Then we can simply use it like so...

if is_online(10):
    print('ONLINE')
else:
    print('OFFLINE')

Or, as an alternative, we can throw it all into one function, make it sleep and basically plonk it anywhere you like.

from time import sleep
from requests import get
from requests.exceptions import ConnectionError

def wait_until_online(timeout, slumber):
    offline = 1
    while offline:
        try:
            r = get("https://google.com", timeout=timeout).status_code
        except ConnectionError:
            r = None
        if r == 200:
            print('ONLINE')
            offline = 0
        else:
            print('OFFLINE')
            sleep(slumber)

And use it like this...

wait_until_online(10, 900)

Thanks for reading. x

Resources