[Tutor] URL test function.

M. George Hansen technopolitica at gmail.com
Fri Oct 22 19:05:59 CEST 2010


> def is_ready():
>
>  with settings(
>
>  warn_only=True
>
>  ):
>
>  try:
>
>   urllib2.urlopen('http://'+env.host_string+'\:8080')
>
>  except urllib2.URLError:
>
>   time.sleep(10)
>
>   urllib2.urlopen('http://'+env.host_string+'\:8080')
>
> I am trying to get the 'host_string' environment variable to plug in here but not sure if the parent function will pass along that information nor if I can call it like this. Additionally, I have never used try/except so I don't know if this will just try twice and quit. As it is now, it raises URLError and bombs out.

Your try..except block does execute the urlopen function twice
(provided the first time fails). The problem is that if the second
attempt also fails and raises an exception within the except clause
there is no handler for the exception and it will probably stop
execution.

I assume that the "settings" context manager may have some means of
turning exceptions into warnings, hence the "warn_only=True" argument,
but for some reason isn't handling URLError exceptions.

You could use nested try..except clauses like so:

def is_ready():
    with settings(warn_only=True):
        try:
            urllib2.urlopen('http://'+env.host_string+'\:8080')
        except urllib2.URLError:
            time.sleep(10)
            try:
                urllib2.urlopen('http://'+env.host_string+'\:8080')
            except urllib2.URLError:
                pass # Or log a warning message, etc.

But this is rather ugly syntax. Instead, I'd suggest using a while loop:

def is_ready():
    max_tries = 2
    try_n = 0
    with settings(warn_only=True):
        while(True):
            try_n += 1
            try:
                urllib2.urlopen('http://'+env.host_string+'\:8080')
            except urllib2.URLError:
                if (try_n < max_tries):
                    # We'll wait and try again...
                    time.sleep(10)
                else:
                    # Maximum number of tries exceeded! Print a
warning message and break
                    # out of the loop
                    break
            else:
                # It worked! So get out of the while loop
                break

This is much more explicit and will allow you to easily change the
maximum number of tries you will allow.


More information about the Tutor mailing list