Time limit for input

I've been looking for this for a while, but I didn't find a way that worked, I want to do this:

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

      

how to add a time limit to this?

+3


source to share


1 answer


If you don't care about thread safe, this is a good approach:



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

      

+2


source







All Articles