Sometimes, we want to add keyboard input with timeout with Python.
In this article, we’ll look at how to add keyboard input with timeout with Python.
How to add keyboard input with timeout with Python?
To add keyboard input with timeout with Python, we can use the select.select
method with sys.stdin
.
For instance, we write:
import sys, select
print("You have 5 seconds to answer")
i, o, e = select.select([sys.stdin], [], [], 5)
if (i):
print("You said", sys.stdin.readline().strip())
else:
print("You said nothing")
We call select.select
with [sys.stdin]
and 5 to given users 5 seconds to enter some text.
If i
is True
, then the user entered something within the time limit and we can read the inputted value with sys.stdin.readline().strip()
.
Conclusion
To add keyboard input with timeout with Python, we can use the select.select
method with sys.stdin
.