python - 在 n 时间后,我将如何停止 while 循环?

标签 python python-2.7

如果 while 循环没有达到我想要的效果,我将如何在 5 分钟后停止它。

while true:
    test = 0
    if test == 5:
        break
    test = test - 1

这段代码让我陷入无限循环。

最佳答案

尝试以下方法:

import time
timeout = time.time() + 60*5   # 5 minutes from now
while True:
    test = 0
    if test == 5 or time.time() > timeout:
        break
    test = test - 1

您可能还想在这里添加一个短暂的 sleep ,这样这个循环就不会占用 CPU(例如 time.sleep(1) 在循环体的开头或结尾)。

关于python - 在 n 时间后,我将如何停止 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13293269/

相关文章:

python - Pandas 新手 - 阅读 Excel - 尝试将公式应用于列

python - sys.version_info 对于 Python 版本检查是否可靠?

python-2.7 - 在窗口和远程 X11 中将 Tkinter 顶级窗口居中?

python-2.7 - Airflow 管理 UI 显示示例 dags

python - 使用 Python 在 JSON 数据中使用 Null 而不是 Nones

python - 如何从自定义对象列表中删除重复项?

Python:通过删除每个第 n 个元素从现有列表构建新列表

python - django CMS 历史选项卡在哪里?

python - 使用 lmfit 和差分进化方法设置迭代限制

python - 从 dict 以列表作为值创建 DataFrame