# input_without_enter_with_timeout_python3.py
# lire une séquence de chaînes validée quand rien pressé pendant timeout secondes (0.5 seconde ici)
# https://stackoverflow.com/questions/28285687/keyboard-input-with-timeout-and-without-press-enter
import sys
from select import select
import tty
import termios
try:
# more correct to use monotonic time where available ...
from time33 import clock_gettime
def time(): return clock_gettime(0)
except ImportError:
# ... but plain old 'time' may be good enough if not.
from time import time
def input_with(timeout, default):
"""Read an input from the user or timeout"""
sys.stdout.flush()
# store terminal settings
old_settings = termios.tcgetattr(sys.stdin)
buff = ''
try:
tty.setcbreak(sys.stdin) # flush per-character
break_time = time() + timeout
while True:
rlist, _, _ = select([sys.stdin], [], [], break_time - time())
if rlist:
c = sys.stdin.read(1)
# swallow CR (in case running on Windows)
if c == '\r':
continue
# newline EOL or EOF are also end of input
if c in ('\n', None, '\x04'):
break # newline is also end of input
buff += c
sys.stdout.flush()
else: # must have timed out
break
finally:
# put terminal back the way it was
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
if buff:
return str(buff.replace('\n','').strip())
else:
return default
def getSequ(prompt1):
"""Attendre une séquence de touches du user"""
print('[getSequ] '+prompt1)
sek = ''
timeout = 0.5 # augmenter pour personnes lentes
default = ''
while True:
gk_touche = input_with(timeout, default)
if sek == '':
if gk_touche != '':
sek = str(gk_touche)
else:
if gk_touche == default:
break
else:
sek = sek + str(gk_touche)
return sek
x = getSequ("Sequence svp")
print("x=" + x)