One way to do this, is to create a separate thread with the standard threading
library. You create a thread, that waits for an input and if it is received, then a variable is modified in the main thread.
The flow goes like:
- Start a thread that waits for input
- Wait the time
- Check if variable in main thread has been modified (pressed too early)
- start the timer and print
GO!
- End timer when the variable in main thread is modified (aka input is provided)
This has the downside, that the message Pressed too early.
is only printed when the wait timer is up.
Here is your modified code:
import random
import time
import threading
print("Reaction Time\nPress Enter when stated 'GO' ")
def get_input(l):
"""This function runs in a new thread and waits for the user to press enter"""
data = input()
l.append(data)
return
inp = []
input_thread = threading.Thread(target=get_input,args=(inp,))
input_thread.start()
print("Wait...")
time.sleep(random.randint(1, 4))
if inp: #Check if list is still empty
print("Pressed too early.")
exit(0)
start = time.time()
print("GO!")
while not inp: #While the list is still empty, run the timer
pass
end = time.time()
diff = end - start
print("\nYou took " + str(diff) + " long")
There is dicussion of a similar problem/tools to solve such problems here: Python: wait for user input, and if no input after 10 minutes, continue with program and Key Listeners in python?