4

I want my python script to check for an active internet connection and if there is one then continue with the execution. If there is NO connection then continue checking. Basically block the execution in "main()" until the script can reconnect.

python

import urllib2

def main():
    #the script stuff

def internet_on():
    try:
        response=urllib2.urlopen('http://74.125.113.99',timeout=1)
        main()
    except urllib2.URLError:
    internet_on()
Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60
Blainer
  • 2,552
  • 10
  • 32
  • 39
  • 5
    Stack Overflow is not your personal research assistant: http://meta.stackexchange.com/a/128553 – Joel Cornett May 15 '12 at 21:56
  • Does this answer your question? [Checking network connection](https://stackoverflow.com/questions/3764291/checking-network-connection) – blong Oct 06 '20 at 15:35

1 Answers1

9

Definitely don't do it recursively. Use a loop instead:

def wait_for_internet_connection():
    while True:
        try:
            response = urllib2.urlopen('http://74.125.113.99',timeout=1)
            return
        except urllib2.URLError:
            pass

def main():
    ...

wait_for_internet_connection()
main()
NPE
  • 486,780
  • 108
  • 951
  • 1,012