簡體   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