Time-Limited User Input in Python
When soliciting user input with the input function, you may want to limit the time the user has to respond. This allows you to gracefully handle timeouts and provide appropriate feedback.
Using a Time-Limited Input
To implement time-limited input, consider the following approaches:
Blocking Thread Approach (Python 2/3)
import threading timeout = 10 # In seconds t = threading.Timer(timeout, lambda: print('Sorry, times up.')) t.start() prompt = "You have {} seconds to choose the correct answer...\n".format(timeout) answer = input(prompt) t.cancel() # Stop the timer if the user provides a response
Non-Blocking Thread Approach (Python 3)
import sys import msvcrt # For Windows import time # For Unix def input_with_timeout(prompt, timeout, timer=time.monotonic): sys.stdout.write(prompt) sys.stdout.flush() endtime = timer() + timeout result = [] while timer() < endtime: if msvcrt.kbhit(): # For Windows # Handle keyboard input else: # For Unix ready, _, _ = select.select([sys.stdin], [], [], timeout) if ready: return sys.stdin.readline().rstrip('\n') raise TimeoutExpired()
Signal Handling Approach (Unix-like systems)
import signal def alarm_handler(signum, frame): raise TimeoutExpired() def input_with_timeout(prompt, timeout): signal.signal(signal.SIGALRM, alarm_handler) signal.alarm(timeout) try: return input(prompt) finally: signal.alarm(0) # Cancel the alarm
Choose the approach that best suits your operating system and blocking requirements.
The above is the detailed content of How Can I Implement Time-Limited User Input in Python?. For more information, please follow other related articles on the PHP Chinese website!