python: 遇到异常重试X次,否则退出
python: retry X times if exception met, exit if not
现在连接成功一次,如果遇到异常,
没有像我希望的那样重试,只是抛出:
Will retry: [Errno 111] Connection refused
如果所有尝试都不成功,它应该 return 为假,如果至少有一个 return 回答
,它应该为真
似乎需要一些复杂的 'while',例如
for attempt in range(attempts) and while True
这是我的代码:
attempts = 10
for attempt in range(attempts):
try:
conn = httplib.HTTPConnection("server:80", timeout=5)
conn.request("GET","/url")
r = conn.getresponse()
except socket.error, serr:
print("Will retry: %s" % serr)
conn.close()
else:
print("OK")
finally:
return False
我也试过:
for attempt in range(attempts):
while True:
try:
同样的结果...
尝试在 while 循环中使用计数器和标志。
def funct():
flag = False
counter = 0
while True:
counter += 1
try:
conn = httplib.HTTPConnection("server:80", timeout=5)
conn.request("GET","/url")
r = conn.getresponse()
flag = True
break
except socket.error, serr:
print("Will retry: %s" % serr)
conn.close()
if counter>9:
break
return flag
现在连接成功一次,如果遇到异常, 没有像我希望的那样重试,只是抛出:
Will retry: [Errno 111] Connection refused
如果所有尝试都不成功,它应该 return 为假,如果至少有一个 return 回答
,它应该为真似乎需要一些复杂的 'while',例如
for attempt in range(attempts) and while True
这是我的代码:
attempts = 10
for attempt in range(attempts):
try:
conn = httplib.HTTPConnection("server:80", timeout=5)
conn.request("GET","/url")
r = conn.getresponse()
except socket.error, serr:
print("Will retry: %s" % serr)
conn.close()
else:
print("OK")
finally:
return False
我也试过:
for attempt in range(attempts):
while True:
try:
同样的结果...
尝试在 while 循环中使用计数器和标志。
def funct():
flag = False
counter = 0
while True:
counter += 1
try:
conn = httplib.HTTPConnection("server:80", timeout=5)
conn.request("GET","/url")
r = conn.getresponse()
flag = True
break
except socket.error, serr:
print("Will retry: %s" % serr)
conn.close()
if counter>9:
break
return flag