繁体   English   中英

我如何才能将布尔值设置为True,并使其满足条件,则变为False,但仅在一定时间内?

[英]How could I set a boolean value to True, and make it so if a condition is met, it becomes False, but only for a certain amount of time?

似乎应该有一个使用time模块的简单解决方案,但我已经尝试了一些方法,但似乎没有任何效果。 我需要这样的工作:

hungry = True
if line.find ('feeds'):
    #hungry = False for 60 seconds, then hungry is true again

有人对此有解决方案吗?

编辑:至于我已经尝试过,我已经尝试了这段代码:

if hungry==True:
     print('yum! not hungry for 20 seconds')
     hungry = False
     i = 20
     while(i>0):
         i-=1
         time.sleep(1)
         if(i==0):
             hungry = True

但这是行不通的,因为该程序只是暂停直到hungry再次变为True为止,而在程序睡眠时hungry为假将无济于事。 在程序的其余部分正常工作的一定时间内,它应该是错误的

编辑:看起来如果没有线程,这将是不可能的。 我将不得不找到一个新的解决方案,或者学习使用线程。 无论如何,感谢您的所有帮助,我非常感谢!

您可以将所需的行为封装在TimedValue类中,但这在这里可能是过大的了-我可能只会做类似的事情

now = time.time()
hunger = lambda: time.time() > now + 60

然后在我需要该值而不是hungry时使用hunger() 这样,代码就不会阻塞,我们可以继续进行工作,但是hunger()将为我们提供正确的状态。 例如

import time
now = time.time()
hunger = lambda: time.time() > now + 60
for i in range(10):
    print 'doing stuff here on loop', i
    time.sleep(10)
    print 'hunger is', hunger()

产生

doing stuff here on loop 0
hunger is False
doing stuff here on loop 1
hunger is False
doing stuff here on loop 2
hunger is False
doing stuff here on loop 3
hunger is False
doing stuff here on loop 4
hunger is False
doing stuff here on loop 5
hunger is True
doing stuff here on loop 6
hunger is True
doing stuff here on loop 7
hunger is True
doing stuff here on loop 8
hunger is True
doing stuff here on loop 9
hunger is True

我不确定您需要哪种精度,但是也许您可以睡60秒然后将变量设置为true?

from time import sleep
hungry = True
if line.find('feeds'):
  hungry = False
  sleep(60)
  hungry = True

您可以按照以下方式进行操作:

from threading import Timer
import time

class Time_out(object):
    def __init__(self,secs):
        self.timer = Timer(secs,self.set_false)
        self.hungry=True
        self.timer.start()

    def set_false(self):
        self.hungry=False

if __name__ == '__main__':
    x=Time_out(1)
    y=0
    t1=time.time()
    while x.hungry:
        y+=1
        # this loop -- do whatever... I just increment y as a test...

    print 'looped for {:.5} seconds, y increased {:,} times in that time'.format(time.time()-t1, y)

印刷品:

looped for 1.0012 seconds, y increased 5,239,754 times in that time

我在这里为超时使用的值是1秒,但是您可以使用自己的值。 然后在while循环中进行工作。 这是一个非常原始但有效的回调。

好处是您可以拥有许多Time_out对象,并且循环将继续进行,直到没人饿为止!

您也可以使用下面的代码。 这是一种优雅的OOP解决方案,使用和维护都很方便。

from time import time

class TimedProperty(object):

    def __init__(self, value1, value2):
        self.value1 = value1
        self.value2 = value2
        self.start_time = -1
        self.time_value = 0

    @property
    def value(self):
        if self.valuenum == 0:
            return self.value1
        else:
            return self.value2

    @property
    def valuenum(self):
        if time() - self.start_time > self.time_value:
            return 0
        else:
            return 1

    def switch_for(self, seconds, value=None):
        self.start_time = time()
        self.time_value = seconds
        if value is not None:
            self.value2 = value

用法:

def main():
    p = TimedProperty(True, False)
    print p.value
    print p.valuenum
    p.switch_for(0.2)
    print p.value
    print p.valuenum
    sleep(0.5)
    print p.value
    print p.valuenum

输出:

True
0
False
1
True
0

在codepad.org上的示例: http ://codepad.org/glujHgey 在codepad 上禁止sleep(),它被替换为cons for loop的时间)

简单的解决方案:

from time import time # time() is the time in seconds since the epoch (January 1st, 1970)
hungry = True
if line.find('feeds'):
    start, hungry = time(), False # it will be a fraction of a second off 
    while 1:                      # because hungry is set to False right 
        if (time() - start) >= 60:  # after start is set to the current time
            hungry = True             
            break  

注意:这可能不完全是60秒,因为time() (至少,我被告知)可能受到程序内存使用的影响; 因此,它可能会稍微偏离。

另外,除非您使用线程,否则您将无法在程序中真正执行其他任何操作。 不过,您可以在while循环中运行程序的其余部分。

编辑:您可以创建一个函数来执行此操作。 因此,您可以运行部分程序,然后检查是否是时候再次更改饥饿值:

def isHungry(start):
     from time import time
     if (time() - start) >= 60: hungry = True # if 60 seconds has passed
     else: hungry = False
     return hungry

from time import time
# some code
if line.find('feeds'):
    start = time()
# a bit of code
hungry = isHungry(start)
# more code
hungry = isHungry(start)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM