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

新手上路,请多包涵

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

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

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

原文由 Adilicious 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 409
2 个回答

尝试以下操作:

 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

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

原文由 Andrew Clark 发布,翻译遵循 CC BY-SA 3.0 许可协议

在这种情况下,您不需要使用 while True: 循环。有一种更简单的方法可以直接使用时间条件:

 import time

# timeout variable can be omitted, if you use specific value in the while condition
timeout = 300   # [seconds]

timeout_start = time.time()

while time.time() < timeout_start + timeout:
    test = 0
    if test == 5:
        break
    test -= 1

原文由 Petr Krampl 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题