Search code examples
pythonpython-3.xpython-requestsexcept

How to monitor internet connectivity using infinite while loop Python?


I am using an infinite while loop to perform specific function if internet is available. And to print an statement if internet is not available. Following is the code.

import requests,time
while True:
    print("HI")
    try:
        requests.get('https://www.google.com/').status_code
        print('online')
    except:
        print('offline')
        

The code works on first run whether internet is running or not. But once internet gets disconnected it get stuck. Nothing prints. any idea?

And is using infinite while loop a good solution for this task ?


Solution

  • You might be experiencing a TIMEOUT. I.E. when INTERNET is disconnected your request gets stuck. You might try adding a timeout to your request like this:

    import requests, time
    
    while True:
        print("HI")
        try:
            requests.get('https://www.google.com/', timeout=5).status_code
            print('online')
        except:
            print('offline')
        # do consider adding a sleep here
        time.sleep(2.5)