How to test a URL request in a "while True" loop

Aahz aahz at pythoncraft.com
Wed Jan 13 20:27:59 EST 2010


In article <mailman.233.1262197919.28905.python-list at python.org>,
Philip Semanchuk  <philip at semanchuk.com> wrote:
>
>While I don't fully understand what you're trying to accomplish by  
>changing the URL to google.com after 3 iterations, I suspect that some  
>of your trouble comes from using "while True". Your code would be  
>clearer if the while clause actually stated the exit condition. Here's  
>a suggestion (untested):
>
>MAX_ATTEMPTS = 5
>
>count = 0
>while count <= MAX_ATTEMPTS:
>    count += 1
>    try:
>       print 'attempt ' + str(count)
>       request = urllib2.Request(url, None, headers)
>       response = urllib2.urlopen(request)
>       if response:
>          print 'True response.'
>    except URLError:
>       print 'fail ' + str(count)

Note that you may have good reason for doing it differently:

MAX_ATTEMPTS = 5
def retry(url):
    count = 0
    while True:
        count += 1
        try:
            print 'attempt', count
            request = urllib2.Request(url, None, headers)
            response = urllib2.urlopen(request)
            if response:
                print 'True response'
        except URLError:
            if count < MAX_ATTEMPTS:
                time.sleep(5)
            else:
                raise

This structure is required in order for the raise to do a proper
re-raise.

BTW, your code is rather oddly indented, please stick with PEP8.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair



More information about the Python-list mailing list