How to Implement a Time Limit for User Input in Python
While utilizing the raw_input() function, you may encounter situations where you wish to terminate input after a predefined duration. Fortunately, Python provides several solutions to address this requirement.
Unix-Only Method:
@jer's suggestion utilizes the signal.alarm function, which is only available on Unix systems. This function raises a KeyboardInterrupt exception when the specified timeout is reached. The following code exemplifies this approach:
import signal def raw_input_with_timeout(prompt, timeout): signal.alarm(timeout) try: return input(prompt) except KeyboardInterrupt: return None finally: signal.alarm(0) # Reset alarm to avoid interference
Cross-Platform and Windows-Specific Methods:
For cross-platform or Windows-specific solutions, consider employing the threading.Timer class along with thread.interrupt_main. This approach sends a KeyboardInterrupt to the main thread from a timer thread. The code below illustrates this method:
import threading def raw_input_with_timeout(prompt, timeout): print(prompt, end=' ') timer = threading.Timer(timeout, thread.interrupt_main) result = None try: timer.start() result = input(prompt) except KeyboardInterrupt: pass timer.cancel() return result
Windows-Specific Method (Untested):
In Windows environments, msvcrt can be used to achieve timeouts. This approach involves polling for keypresses within a tight loop and accumulating input until a maximum time is reached or a newline character is detected.
import msvcrt import time def raw_input_with_timeout(prompt, timeout): print(prompt, end=' ') finishat = time.time() + timeout result = [] while True: if msvcrt.kbhit(): result.append(msvcrt.getche()) if result[-1] == '\r': return ''.join(result) time.sleep(0.1) else: if time.time() > finishat: return None
Customizable Behavior:
In case a timeout return value other than None is desired, simply replace the return None statement in the above code snippets. Additionally, adjusting finishat after each keystroke can adjust timeouts based on input pacing.
The above is the detailed content of How to Implement a Time Limit for User Input in Python?. For more information, please follow other related articles on the PHP Chinese website!