2016-03-04 64 views
1

我有一个尝试循环执行后函数需要一些时间来工作:如何跳出for并尝试循环时刻我的代码工作?

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

break语句终止当前循环,在您的示例中为while循环。您可以在print声明之后放置另一个break来终止for环路:

... 
print "SUCCESS" 
break