-
Notifications
You must be signed in to change notification settings - Fork 0
/
keyinput.py
57 lines (54 loc) · 1.67 KB
/
keyinput.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import os, queue, threading
if os.name == "nt":
import msvcrt, time
elif os.name == "posix":
import sys, tty, termios, select
else:
raise OSError("Unknown OS type")
def listen_key(timeout = None):
"""
Returns returned value of _listen_key_{os name}.
type of the timeout should be integer.
timeout value will be set to 0 if nothing were given.
"""
if timeout == None:
timeout = 0
elif type(timeout) != int:
raise ValueError("'timeout' argument only accepts integer value")
if os.name == "nt":
return _listen_key_nt(timeout)
elif os.name == "posix":
return _listen_key_posix(timeout)
def _listen_key_posix(timeout):
"""
listen to the keypress until it reaches timeout and returns pressed key.
return type is str.
returns None if nothing was pressed.
"""
oldsettings = termios.tcgetattr(sys.stdin.fileno())
tty.setcbreak(sys.stdin)
try:
selresult = select.select([sys.stdin], [], [], timeout)
isdata = selresult[0] != []
if isdata:
key = sys.stdin.read(1)
else:
key = None
finally:
termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, oldsettings)
return key
def _listen_key_nt(timeout):
"""
listen to the keypress until it reaches timeout and returns pressed key.
return type is str.
returns None if nothing was pressed.
"""
starttime = time.time()
while True:
if msvcrt.kbhit():
try:
return msvcrt.getch().decode()
except UnicodeDecodeError:
return None
if time.time() - starttime >= timeout:
return None