Asynchronous Keyboard Input with Timeout Handling
The task at hand is to solicit user input while imposing a timeout to prevent indefinite waiting. While Google suggests a mailing thread for this, it may not yield satisfactory results.
The challenge arises from the system input function ([raw_]input) accepting at most one argument. However, to implement a timeout, one must pass a timeout parameter. This results in a TypeError.
Solution using Select Poll
A more reliable solution involves using the select.select() system call:
import sys, select print("You have ten seconds to answer!") i, o, e = select.select([sys.stdin], [], [], 10) if (i): print("You said", sys.stdin.readline().strip()) else: print("You said nothing!")
Breakdown
This approach offers greater portability and efficiency in handling keyboard input with timeout functionality.
The above is the detailed content of How Can I Get Asynchronous Keyboard Input with a Timeout in Python?. For more information, please follow other related articles on the PHP Chinese website!