1

Using an input() statement in python stops the entirety of your code until the user enters something in. My goal is to wait for an input, then, if the user has done nothing, after some time the input statement will break and continue with the rest of the program.

It would work somewhat like:

import time
import threading

def ask_for_input():
    input("Press Enter to Continue...")

t1 = threading.Thread(target=ask_for_input)
t1.start()

time.sleep(10)
#break out of input statement

The problem with just continuing with the rest of the code after time.sleep(10) is that if you try to ask for user input again, the user must first break out of that first input statement to type something in the next one. Meaning that if I tried something like this:

...
time.sleep(10)
input("Press Enter Again to Continue")

The user would not see "Press Enter Again to Continue" until they have broken out of the first input statement. They would have to press enter twice to continue.

To clarify a little bit, I'm not looking for the input statement to break at a set time. Rather, I'd like to be able to trigger it's exit using some sort of function or flag. Is there any way to do this?

mimky
  • 146
  • 7

1 Answers1

2

There is a python library to achieve exactly this behaviour. Take a look at inputimeout.
From the documentation:

from inputimeout import inputimeout, TimeoutOccurred
try:
    something = inputimeout(prompt='>>', timeout=5)
except TimeoutOccurred:
    something = 'something'
print(something)
S. Ferard
  • 221
  • 2
  • 9
  • Would there be a way to utilize this module by calling a function later in the code to trigger a timeout? I'd like for it to not be dependent on a set time. – mimky Nov 18 '20 at 05:30
  • Unfortunately there is not. Turns out that interrupting a user input in another thread isn't that easy – S. Ferard Nov 18 '20 at 06:30