Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python wait until connection active

Tags:

python

urllib

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()
like image 240
Blainer Avatar asked Feb 20 '23 11:02

Blainer


1 Answers

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()
like image 77
NPE Avatar answered Feb 25 '23 15:02

NPE