一日一技:如何實(shí)現(xiàn)帶timeout的input?

我們知道,在Python里面,可以使用input獲取用戶的輸入。例如:

但有一個問題,如果你什么都不輸入,程序會永遠(yuǎn)卡在這里。有沒有什么辦法,可以給input設(shè)置超時時間呢?如果用戶在一定時間內(nèi)不輸入,就自動使用默認(rèn)值。
要實(shí)現(xiàn)這個需求,在Linux/macOS系統(tǒng)下面,我們可以使用selectors。這是Python自帶的模塊,不需要額外安裝。對應(yīng)的代碼如下:
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
運(yùn)行效果如下圖所示:

selectors[1]這個模塊,可以使用系統(tǒng)層級的select,實(shí)現(xiàn)IO多路復(fù)用。
這段代碼來自inputimeout[2]。上面除了Linux/macOS版本外,還有Windows版本。大家有興趣可以看一下。
參考資料
selectors: https://docs.python.org/3.8/library/selectors.html
[2]inputimeout: https://github.com/johejo/inputimeout/blob/master/inputimeout/inputimeout.py


評論
圖片
表情
