python - Python如何自动跳出死循环?

标签 python

我在 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/

相关文章:

python - 无需中间体的 Numpy 索引

python - 如何将深度为 2 的元组转换为 2D Numpy 数组?

Python:插入列表比 O(N) 更快?

python - 使用 Python 范围和日历检查闰年

python - 按地址获取 'erc-20' 交易的列表

python - 如何在 PyQt4 创建的 GUI 中以丰富的格式显示一些不可编辑的文本?

python - 自定义 PyQt Qscintilla CPP 词法分析器

python - 无法从布局复杂的表中抓取三个字段

python - 错误 : invalid command 'build_sphinx'

python - 升级后 pip 不起作用