One skill a day: How to implement input with timeout?

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 import sys
import selectors

def timeout_input (msg, default= '' , timeout= 5 ) :
sys.stdout.write(msg)
sys.stdout.flush()
sel = selectors.DefaultSelector()
sel.register(sys.stdin, selectors.EVENT_READ)
events = sel.select(timeout)
if events:
key, _ = events[ 0 ]
return key.fileobj.readline().rstrip()
else :
sys.stdout.write( '\n' )
return default

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.

Leave a Comment