gpt4 book ai didi

python - 如何在我的代码工作时跳出 for 和 try 循环?

转载 作者:太空宇宙 更新时间:2023-11-03 16:51:50 25 4
gpt4 key购买 nike

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

我只想运行 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循环?

最佳答案

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

 ...
print "SUCCESS"
break

关于python - 如何在我的代码工作时跳出 for 和 try 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35787250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com