【问题标题】:Python if condition true for x amount of timePython如果条件为真x时间
【发布时间】:2018-07-10 19:29:36
【问题描述】:

我想创建一个仅在 a 为 True 超过 3 秒时才执行的条件。我希望它像这样工作。

if a == True for more than 3 seconds:
   dosomething

【问题讨论】:

  • 达到这个条件是不是要等三秒?
  • 你需要你的程序在这三秒内做点什么吗?如果不是:我会检查条件,如果为真--> 等待 3 秒,也就是 time.sleep(3),然后再次检查条件
  • 这种情况怎么可能从 True 变为 False?你有后台线程运行吗?还是后台进程?还是什么?
  • 是的 time.sleep() 不起作用,因为我的脚本停止运行

标签: python if-statement


【解决方案1】:

如果要检查该值是否在 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

由于 bool 类型是不可变的,因此如果对象 id 发生变化,它就会发生变化。

如果您想检查 3 秒后是否已更改,请执行以下操作。如果任何线程在 3 秒内更改了 a,它就会捕获到。

import time
time.sleep(3)
if a:
   dosomething

【讨论】:

  • time.sleep() 停止我的脚本,我仍然需要它运行
  • 你能发布回溯吗?
【解决方案2】:

简单的解决方案(灵感来自 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

【讨论】:

    【解决方案3】:
    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 
    

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 2021-09-22
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多