如果发生错误,请在循环中重复迭代
是否有命令(如break
和continue
)可以重复最近的迭代?如果发生错误,请在循环中重复迭代
例如,抛出异常时。
for i in range(0,500):
try:
conn = getConnection(url+str(i))
doSomething(conn)
except:
repeat
让我们有一个迭代,其中i
变量的值是6
。在此迭代过程中发生了一些连接错误。我想重复这个迭代。
有没有可以做到的命令?
我当然可以这样做:
i=0
while i!=500:
try:
conn = getConnection(url+str(i))
doSomething(conn)
i+=1
except:
pass
没有,还有就是“倒带”一个for循环Python中没有命令。
你可以使用一个while True:
循环中的for循环:
for i in range(500):
while True:
try:
conn = getConnection(url+str(i))
doSomething(conn)
except Exception: # Replace Exception with something more specific.
continue
else:
break
或不else:
:
for i in range(500):
while True:
try:
conn = getConnection(url+str(i))
doSomething(conn)
break
except Exception: # Replace Exception with something more specific.
continue
但我个人认为,你提出的解决方案是更好,因为它避免了压痕水平。
bare' except'使得不用停止'kill -9'就可以停止这个程序。 – 2014-12-01 21:31:34
是的,我专注于循环,忽略了这一点。固定。 – iCodez 2014-12-01 21:33:19
为什么不使用if
声明?
n=6
i=0
while i!=500:
failed = False;
try:
conn = getConnection(url+str(i))
doSomething(conn)
i+=1
except:
#handle error
failed = True;
#try again if n-th case failed first time
if(i == n and failed):
try:
conn = getConnection(url+str(i))
doSomething(conn)
except:
#handle error
您可以使用发电机:
def process_connections(n_connections, url, max_tries=50):
i = 0
try_count = 0
while i < n_connections:
try:
conn = getConnection(url+str(i))
yield conn
except:
try_count += 1
if try_count > max_tries:
raise Exception("Unable to connect after %s tries" % max_tries)
else:
i += 1 # increments only if no exception
你执行你的操作:
for conn in process_connections(500, url):
do_something(conn)
如果连接有问题,是否可能有无限循环? – Marichyasana 2014-12-01 21:33:20
是的,你是对的,我会改变一下代码。 – 2014-12-01 21:36:17
for i in range(500):
while True
try:
conn = getConnection(url+str(i))
break
except Exception: # still allows to quit with KeyboardInterrupt
continue
do_your_stuff()
这看起来有点冒险,但是,你至少应该内启用一些日志记录一个while
块。
如果您希望在更多的地方使用它,你可以写一个简单的装饰:
def keep_trying(fn, *args, **kwargs):
def inner(*args, **kwargs):
while True:
try:
return fn(*args, **kwargs)
except Exception:
continue
return inner
# later you can use it simple like this:
for i in range(500):
conn = keep_trying(getConnection)(url+str(i))
可以使用嵌套的for循环来把帽子放在你重试操作的次数。这基本上是@ PierreAlex的生成器答案,但没有额外的函数定义。
for i in range(500):
for retry in range(10):
try:
conn = getConnection(url+str(i))
doSomething(conn)
except Exception: # Replace Exception with something more specific.
time.sleep(1)
else:
print "iteration", i, "failed"
有没有什么语法可以让Python做到这一点,如果这就是你要求的。你总是可以在except子句中重试同样的功能,虽然 – Greg 2014-12-01 21:22:26
你可以使用生成器,产生每个成功的连接 – 2014-12-01 21:32:59