如何设置布尔值为True,并在满足条件时在有限时间内变为False?
看起来应该有个简单的方法可以用 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
是 False 也没用;它应该在一段时间内保持为 False,同时让程序的其他部分继续运行。
补充:看起来如果不使用线程的话,这个问题是没法解决的。我得么找个新方法,么就是学习怎么用线程。无论如何,感谢大家的帮助,我真的很感激!
5 个回答
1
你可以按照以下方式操作:
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
对象,循环会一直进行,直到大家都不再饿为止!
1
我不太确定你需要什么样的准确性,不过你可以试试先等60秒,然后再把那个变量设置为真吗?
from time import sleep
hungry = True
if line.find('feeds'):
hungry = False
sleep(60)
hungry = True
3
你可以把你想要的行为放在一个叫做 TimedValue
的类里面,但这样可能有点复杂。其实我可能会直接做一些简单的事情,比如:
now = time.time()
hunger = lambda: time.time() > now + 60
然后在需要获取值的时候用 hunger()
,而不是直接用 hungry
。这样的话,代码就不会卡住,我们可以继续做其他事情,而 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