[英]python: retry X times if exception met, exit if not
now it works once if connected successfully, but if exception is met, it doesn't retry as I wish, just throwing:现在如果连接成功,它会工作一次,但如果遇到异常,它不会按我的意愿重试,只是抛出:
Will retry: [Errno 111] Connection refused
It should return False if all attempts weren't successful and True if at least one returned an answer如果所有尝试都没有成功,它应该返回 False ,如果至少有一个返回答案,它应该返回 True
Seems there's something complicated with 'while' needed, like似乎需要一些复杂的“while”,比如
for attempt in range(attempts) and while True
Here's my code:这是我的代码:
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
I tried also:我也试过:
for attempt in range(attempts):
while True:
try:
The same result...同样的结果...
Try using a counter and a flag inside a while loop.尝试在 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.