如何突破我的代码工作的for和try循环时刻?

时间:2016-03-04 03:09:35

标签: python for-loop while-loop try-catch

我有一个执行post函数的try循环,需要一些时间才能工作:

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"

我只想运行newproj = proj.post('docs/recalc')一次,如果它运行没有错误,退出。

然而,在运行上述功能后,我在屏幕上显示此输出:

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

为什么即使在我需要成功运行的代码行之后它仍然继续循环?我认为休息意味着走出for循环?

1 个答案:

答案 0 :(得分:1)

break语句终止当前循环,即示例中的while循环。您可以在break语句后添加另一个print来终止for循环:

 ...
 print "SUCCESS"
 break