使用倒数计时器跳出while循环Python

使用倒数计时器跳出while循环Python

本文介绍了使用倒数计时器跳出while循环Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将转到代码向您展示,我试图在计时器结束时停止while循环。有办法吗?

I'll just get to the code to show you, I'm trying to stop my while loop when my timer is over. Is there a way to do that?

from threading import Timer

def run(timeout=30, runs):
    timer(timeout)
    while runs > 0 or over():
        #Do something
        print "start looping"

def timer(time):
    t = Timer(time, over)
    print "timer started"
    t.start()

def over():
    print "returned false"
    return False

如您所见,我正在尝试使用函数 over()停止我的while循环。目前,当我的时间停止时,结束返回为false,但这不会影响我的while循环。我一定做错了什么。

As you can see, I'm trying to use the function over() to stop my while loop. Currently, when my time stop, over is returned as false, but it doesn't affect my while loop. I must be doing something wrong.

所以 Timer 对象允许我做的是传递函数参数,以便当计时器结束时,它会调用该函数 over()。当 over()返回 False 时,它不会直接实时影响while循环。我是否需要回调以隐式强制为假,或者我的停止方法完全错误并且无法正常工作。

So what Timer object allows me to do is to pass a function param so that when the timer is over, it calls that function, over(). As over() returns False, it doesn't directly affect the while loop in real time. Will I need a callback to implicitly force the while to be false or is my method of stopping is completly faulty and will not work.

推荐答案

更改




  • 当计时器到期时,您需要更改状态,以便当调用 over 时,它将返回 True 。现在,为了简单起见,我将其保持在全局状态。您将需要在某些时候进行更改。

  • 此外,您的while循环条件中存在逻辑错误。我们需要确保它仍然可以运行并且并且没有结束。

  • Changes

    • When your timer expires, you need to change the state so that when over is invoked, it will return True. Right now, I keep that in global state for simplicity. You will want to change this at some point.
    • Also, you had a logic error in your while loop condition. We need to make sure it still has runs and is not over.
    • #!/usr/bin/env python
      
      from threading import Timer
      
      globalIsOver = False
      
      def run(runs, timeout=30):
          timer(timeout)
          while runs > 0 and not over():
              #Do something
              print "start looping"
          print 'Exited run function.'
      
      def timer(time):
          t = Timer(time, setOver)
          print "timer started"
          t.start()
      
      def setOver():
          global globalIsOver
          print '\nSetting globalIsOver = True'
          globalIsOver = True
      
      def over():
          global globalIsOver
          print 'returned = ' + str(globalIsOver)
          return globalIsOver
      
      run(100000000, timeout=2)
      

      2秒后返回以下内容:

      This returns the following after the 2 seconds have expired:

      ...
      start looping
      returned = False
      start looping
      returned = False
      start looping
      returned = False
      Setting globalIsOver = True
      
      start looping
      returned = True
      Exited run function.
      

      这篇关于使用倒数计时器跳出while循环Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:27