-
Notifications
You must be signed in to change notification settings - Fork 0
/
keyboard.py
70 lines (60 loc) · 1.89 KB
/
keyboard.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
58
59
60
61
62
63
64
65
66
67
68
69
70
import os
import time
import atexit
# this only works on linux, don't bother on windows
try:
import termios
import fcntl
except ImportError:
print("\nWARNING: Keyboard input only runs on Linux!\n")
pass
import sys, os
import select
def init():
fd = sys.stdin.fileno()
# save old state
flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)
attrs_save = termios.tcgetattr(fd)
# make raw - the way to do this comes from the termios(3) man page.
attrs = list(attrs_save) # copy the stored version to update
# iflag
attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK
| termios.ISTRIP | termios.INLCR | termios. IGNCR
| termios.ICRNL | termios.IXON )
# oflag
attrs[1] &= ~termios.OPOST
# cflag
attrs[2] &= ~(termios.CSIZE | termios. PARENB)
attrs[2] |= termios.CS8
# lflag
attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON
| termios.ISIG | termios.IEXTEN)
termios.tcsetattr(fd, termios.TCSANOW, attrs)
# turn off non-blocking
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)
# read a single keystroke
return (flags_save, attrs_save)
def stop(state):
fd = sys.stdin.fileno()
# restore old state
termios.tcsetattr(fd, termios.TCSAFLUSH, state[1])
fcntl.fcntl(fd, fcntl.F_SETFL, state[0])
def read_single_keypress():
state = init()
r, w, e = select.select([sys.stdin], [], [], 0.000)
input = ' '
for s in r:
if s == sys.stdin:
input = sys.stdin.read(1)
break
stop(state)
return input
def read_single_event():
return ord(read_single_keypress()) # return unicode key value
if __name__ == "__main__":
while True:
key = read_single_event()
if key == ord('q'):
break
elif key != ord(' '):
print ("%s pressed\r" % key)