我在 Python 中有一个“do..., until...”结构如下:
while True:
if foo() == bar():
break
在大多数情况下,它工作正常(最终跳出)。但是,在某些条件永远不会满足的情况下,它会卡在那里。
弄清楚这些情况是什么有点困难,因为它本质上是一个随机过程。所以我想为 while
循环设置一个“超时”。
比如说,如果循环已经运行了 1 秒,但仍未停止,我希望循环自行终止。
我该怎么做?
更新:这是实际代码:
while True:
possibleJunctions = junctionReachability[junctions.index(currentJunction)]
nextJunction = random.choice(filter(lambda (jx, jy): (jx - currentJunction[0]) * (endJunction[0] - currentJunction[0]) > 0 or (jy - currentJunction[1]) * (endJunction[1] - currentJunction[1]) > 0, possibleJunctions) or possibleJunctions)
if previousJunction != nextJunction: # never go back
junctionSequence.append(nextJunction)
previousJunction = currentJunction
currentJunction = nextJunction
if currentJunction == endJunction:
break
最佳答案
import time
loop_start = time.time()
while time.time() - loop_start <= 1:
if foo() == bar():
break
关于python - Python如何自动跳出死循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18950913/