Merge branch '2.0.x-maintenance' into master-merge-commit
[ExpressLRS.git] / src / python / inputimeout / inputimeout.py
blob3b2f7e3d7d18cde18cdc9df56954b2ac6be7608d
1 import sys
3 DEFAULT_TIMEOUT = 30.0
4 INTERVAL = 0.05
6 SP = ' '
7 CR = '\r'
8 LF = '\n'
9 CRLF = CR + LF
12 class TimeoutOccurred(Exception):
13 pass
16 def echo(string):
17 sys.stdout.write(string)
18 sys.stdout.flush()
21 def posix_inputimeout(prompt='', timeout=DEFAULT_TIMEOUT):
22 echo(prompt)
23 sel = selectors.DefaultSelector()
24 sel.register(sys.stdin, selectors.EVENT_READ)
25 events = sel.select(timeout)
27 if events:
28 key, _ = events[0]
29 return key.fileobj.readline().rstrip(LF)
30 else:
31 echo(LF)
32 termios.tcflush(sys.stdin, termios.TCIFLUSH)
33 raise TimeoutOccurred
36 def win_inputimeout(prompt='', timeout=DEFAULT_TIMEOUT):
37 echo(prompt)
38 begin = time.monotonic()
39 end = begin + timeout
40 line = ''
42 while time.monotonic() < end:
43 if msvcrt.kbhit():
44 c = msvcrt.getwche()
45 if c in (CR, LF):
46 echo(CRLF)
47 return line
48 if c == '\003':
49 raise KeyboardInterrupt
50 if c == '\b':
51 line = line[:-1]
52 cover = SP * len(prompt + line + SP)
53 echo(''.join([CR, cover, CR, prompt, line]))
54 else:
55 line += c
56 time.sleep(INTERVAL)
58 echo(CRLF)
59 raise TimeoutOccurred
62 try:
63 import msvcrt
65 except ImportError:
66 import selectors
67 import termios
69 inputimeout = posix_inputimeout
71 else:
72 import time
74 inputimeout = win_inputimeout