【问题标题】:How to break out of a for and try loop moment my code work?如何打破 for 并尝试循环时刻我的代码工作?
【发布时间】:2016-03-04 03:09:34
【问题描述】:

我有一个执行 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

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

【问题讨论】:

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


    【解决方案1】:

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

     ...
     print "SUCCESS"
     break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      相关资源
      最近更新 更多