一日一技:如何實現(xiàn)帶Timeout的Input?
我們知道,在Python里面,可以使用input獲取用戶的輸入。例如:
但有一個問題,如果你什么都不輸入,程序會永遠卡在這里。有沒有什么辦法,可以給input設置超時時間呢?如果用戶在一定時間內(nèi)不輸入,就自動使用默認值。
要實現(xiàn)這個需求,在Linux/macOS系統(tǒng)下面,我們可以使用selectors。這是Python自帶的模塊,不需要額外安裝。對應的代碼如下:
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
運行效果如下圖所示:
selectors[1]這個模塊,可以使用系統(tǒng)層級的select,實現(xiàn)IO多路復用。
這段代碼來自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