[Tutor] URL test function.
M. George Hansen
technopolitica at gmail.com
Fri Oct 22 19:05:59 CEST 2010
> def is_ready():
> with settings(
> except urllib2.URLError:
> 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
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:
pass # Or log a warning message, etc.
But this is rather ugly syntax. Instead, I'd suggest using a while loop:
max_tries = 2
try_n = 0
try_n += 1
if (try_n < max_tries):
# We'll wait and try again...
# Maximum number of tries exceeded! Print a
warning message and break
# out of the loop
# It worked! So get out of the while loop
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