[英]How to break out of a for and try loop moment my code work?
I have a try loop that executes a post function which takes some time to work: 我有一个try循环,它执行一个post函数,这需要一些时间才能工作:
def recalc_proj(proj):
for x in range(0,10):
while True:
try:
newproj = proj.post('docs/recalc')
except someError:
print "another job is running. waiting 10s"
time.sleep(10)
continue
break
print "SUCCESS"
i only want to run newproj = proj.post('docs/recalc')
once and if it runs without error, quit. 我只想运行一次newproj = proj.post('docs/recalc')
,如果运行没有错误,请退出。
However, after running the function above, i get this output on the screen: 但是,运行上面的功能后,我在屏幕上得到以下输出:
another job is running. waiting 10s
another job is running. waiting 10s
another job is running. waiting 10s
another job is running. waiting 10s
SUCCESS
another job is running. waiting 10s
another job is running. waiting 10s
another job is running. waiting 10s
Why does it continue looping even after the line of code i need successfully runs? 为什么即使我需要的代码行成功运行,它仍继续循环? i thought the break means to get out of the for loop? 我以为休息意味着要退出for循环?
The break
statement terminates the current loop, which is the while
loop in your example. break
语句终止当前循环,在您的示例中为while
循环。 You can put another break
after your print
statement to terminate the for
loop as well: 您也可以在print
语句后再加上一个break
以终止for
循环:
...
print "SUCCESS"
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.