Home > Article > Backend Development > How Can I Implement a Timeout for User Input in Python?
In Python, the raw_input() function prompts the user for input, but it waits indefinitely until the user enters something. For situations where you need to impose a time limit on user input, a solution is available using the threading module.
The raw_input_with_timeout() function, as proposed by a user, takes two arguments: prompt (the text displayed to the user) and timeout (the time limit in seconds). It starts a timer thread that will interrupt the main thread after the specified timeout.
Here's an improved version of the code:
import threading def raw_input_with_timeout(prompt, timeout=30.0): print(prompt, end=' ') timer = threading.Timer(timeout, thread.interrupt_main) astring = None try: timer.start() astring = input(prompt) except KeyboardInterrupt: pass timer.cancel() return astring
If the user enters input before the timeout, the input is returned as a string. If the timeout is reached, None is returned to indicate that the user did not provide input within the specified time frame.
Note that this solution assumes that the user is not typing very slowly. If you need to account for slow typing, you could recompute finishat (the time at which the timeout occurs) after every character input.
The above is the detailed content of How Can I Implement a Timeout for User Input in Python?. For more information, please follow other related articles on the PHP Chinese website!