似乎应该有一个使用 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 将无济于事;在程序的其余部分工作时,它应该在一定时间内为假
编辑:如果没有线程,这似乎是不可能的。我将不得不找到一个新的解决方案,或者学习使用线程。无论如何,感谢所有帮助,我非常感谢!
最佳答案
您可以将您想要的行为封装在 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
关于python - 我如何将 boolean 值设置为 True,并使其在满足条件时变为 False,但仅限于一定时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14430399/