对输入施加时间限制

时间:2017-06-05 23:42:32

标签: python-3.x time

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

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

如何为此添加时间限制?

1 个答案:

答案 0 :(得分:2)

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

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()