Search code examples
pythonioerror

Bypass Python IOError while disconnected from network?


Hi there does any one know how can i pass thru IOError? Basicly i have python script that is trying to scraping/getting data from my website via urllib. But when i am disconnected from network i got:

IOError: [Errno socket error] [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

How can i tell to python - keep trying until I will be connected?

for example:

currtokenurl = "http://www.example.com/heady"

f = urllib.urlopen(currtokenurl)
currtoken = f.read()

Thanks.


Solution

  • Put it in a loop so that you can catch the error and retry. Many errors should not be retried, so create a list of the ones you like.

    import time
    import errno
    
    retry_this = [errno.ETIMEOUT,]
    
    currtokenurl = "http://www.example.com/heady"
    
    while True:
        try:
            f = urllib.urlopen(currtokenurl)
            break
        except IOError, e:
            if e.errno in retry_this:
                time.sleep(10)
            else:
                raise
    currtoken = f.read()
    

    It could be that the remote end is not connected, so you may want a way to limit this while loop and give up completely.