一日一技:如何實(shí)現(xiàn)帶Timeout的Input?
我們知道,在Python里面,可以使用input獲取用戶的輸入。例如:
但有一個(gè)問題,如果你什么都不輸入,程序會(huì)永遠(yuǎn)卡在這里。有沒有什么辦法,可以給input設(shè)置超時(shí)時(shí)間呢?如果用戶在一定時(shí)間內(nèi)不輸入,就自動(dòng)使用默認(rèn)值。
要實(shí)現(xiàn)這個(gè)需求,在Linux/macOS系統(tǒng)下面,我們可以使用selectors。這是Python自帶的模塊,不需要額外安裝。對(duì)應(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]這個(gè)模塊,可以使用系統(tǒng)層級(jí)的select,實(shí)現(xiàn)IO多路復(fù)用。
這段代碼來自inputimeout[2]。上面除了Linux/macOS版本外,還有Windows版本。大家有興趣可以看一下。
參考資料
[1] selectors: https://docs.python.org/3.8/library/selectors.html
[2] inputimeout: https://github.com/johejo/inputimeout/blob/master/inputimeout/inputimeout.py