Original link: https://www.kingname.info/2022/07/13/input-timeout/
We know that in Python, you can use input
to get user input. E.g:
But there is a problem, if you don’t enter anything, the program will be stuck here forever. Is there any way to set a timeout for the input
? If the user does not enter within a certain period of time, the default value is automatically used.
To achieve this requirement, under Linux/macOS system, we can use selectors
. This is a module that comes with Python and does not require additional installation. The corresponding code is as follows:
1 |
import sys |
The operation effect is shown in the following figure:
The selectors module can use system-level select
to implement IO multiplexing.
This code is from inputimeout . In addition to the Linux/macOS version above, there is also a Windows version. Anyone interested can take a look.
This article is reprinted from: https://www.kingname.info/2022/07/13/input-timeout/
This site is for inclusion only, and the copyright belongs to the original author.