【问题标题】:Putting a time restriction on input对输入施加时间限制
【发布时间】:2017-11-06 20:06:37
【问题描述】:

我已经搜索了一段时间,但我没有找到有效的方法 我想做的是这样的:

prompt=str(input('press "l" within two seconds:'):
    if prompt=='l':
        print('ta da')
    else:
        print('loser')

如何添加时间限制?

【问题讨论】:

    标签: python-3.x time


    【解决方案1】:

    如果您不关心线程安全,这是一个很好的方法:

    import datetime
    import threading
    win = False
    time_out = False
    def MyThread1(t_name, prompt, time_var):
        global win
        global time_out
        prompt=str(input('press "l" within two seconds:'))
        win = False
        if(not time_out and prompt == 'l'):
          win = True
          print('ta da')
        else:
          print('loser')
    
    def MyThread2(t_name, prompt, time_var):
      global win
      global time_out
      while (time_var > datetime.datetime.now()):
        pass
      time_out = True
    
    time_var = datetime.datetime.now() + datetime.timedelta(seconds=2)
    prompt = 'l'
    
    t1 = threading.Thread(target=MyThread1, args=("Thread-1", prompt, time_var))
    t2 = threading.Thread(target=MyThread2, args=("Thread-2", prompt, time_var))
    t1.start()
    t2.start()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多