[英]Python if condition true for x amount of time
我想創建一個僅在a為True的情況下執行超過3秒的條件。 我希望它像這樣工作。
if a == True for more than 3 seconds:
dosomething
如果要檢查該值3秒鍾沒有變化。
import time
id_a_old = id(a)
time.sleep(3)
id_a_new = id(a)
if id_a_old == id_a_new: # assumes that a is initially true
dosomething
由於布爾類型是不可變的,因此如果更改,則對象ID也會更改。
如果要在3秒鍾后檢查是否已更改,請執行以下操作。 如果任何線程在3秒鍾內更改a
,它將捕獲該線程。
import time
time.sleep(3)
if a:
dosomething
簡單的解決方案(基於Marlon Abeykoon的解決方案):
import time
startTime = time.time()
while a == True:
endTime = time.time()
#do other stuff
if (endTime - startTime > 3):
print("Longer than 3 seconds")
break
import time
a = True
x = int(time.time())
xa = a
while 1:
if a == True and xa == a and int(time.time()) == x + 3:
# dosomething
print "A is True for 3 seconds"
break
if(xa != a):
# dosomething
print "Value of alfa changed from %s to %s in less than 3 seconds" %(xa, a)
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.