Home > Article > Backend Development > How to Implement Time-Limited User Input in Python Using `raw_input()`?
Time-Limited User Input with Raw Input
In Python, the raw_input() function can be used to prompt the user for input. However, there may be scenarios where you want to limit the waiting time for user input to avoid indefinitely holding up the program.
Solution Using Threading Timer
For cross-platform and Windows-specific solutions, you can utilize threading.Timer from the threading module. Import the necessary modules:
import thread import threading
Define a function called raw_input_with_timeout:
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
This function prints the prompt, starts a timer, and prompts for user input using input. If the user takes longer than the specified timeout to input, the timer interrupts the main thread, causing a KeyboardInterrupt exception to be raised. The timer is canceled to prevent further interruptions.
If the input times out, it will return None. If the user provides input before the timeout, it will return the inputted string.
Note:
The above is the detailed content of How to Implement Time-Limited User Input in Python Using `raw_input()`?. For more information, please follow other related articles on the PHP Chinese website!