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
.
import requests
import time
def wait_until_online(timeout, max_attempts, slumber):
attempts = 0
while True:
try:
r = requests.get('https://google.com', timeout=timeout).status_code
except requests.ConnectionError:
r = None
if r == 200:
print('ONLINE')
return True
else:
attempts += 1
print(f'OFFLINE {attempts}/{max_attempts} - Trying again in {slumber}s')
if attempts == max_attempts:
print('NO INTERNET - Shutting down...')
quit()
time.sleep(slumber)
wait_until_online(30, 1, 100)
And use it like this...
wait_until_online(30, 3, 1)
Thanks for reading. x
Resources
- Python: https://python.org
- Requests: http://docs.python-requests.org/en/latest