-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkbthread.py
More file actions
80 lines (67 loc) · 1.97 KB
/
kbthread.py
File metadata and controls
80 lines (67 loc) · 1.97 KB
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
71
72
73
74
75
76
77
78
79
80
from threading import Thread
import signal
import sys
import os
if os.name == 'nt':
import msvcrt
else:
import termios
import atexit
keys = []
def kb():
if os.name == 'nt':
codes = {
b'\x48': 'up',
b'\x50': 'down',
b'\x4d': 'right',
b'\x4b': 'left'
}
else:
codes = {
'A': 'up',
'B': 'down',
'C': 'right',
'D': 'left'
}
while True:
if os.name == 'nt':
key = msvcrt.getch()
keys.append(key)
if len(keys) > 1 and keys[0] == b'\xe0':
keys.pop(0)
keys[0] = codes[keys[0]]
elif len(keys) == 1 and keys[0] != b'\xe0':
keys[0] = keys[0].decode('cp1251')
else:
key = sys.stdin.read(1)
keys.append(key)
if len(keys) == 3 and keys[0] == '\x1b':
keys.pop(0)
keys.pop(0)
keys[0] = codes[keys[0]]
def set_normal_term():
if not os.name == 'nt':
termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)
if not os.name == 'nt':
fd = sys.stdin.fileno()
new_term = termios.tcgetattr(fd)
old_term = termios.tcgetattr(fd)
# New terminal setting unbuffered
new_term[3] = (new_term[3] & ~termios.ICANON & ~termios.ECHO)
termios.tcsetattr(fd, termios.TCSAFLUSH, new_term)
# Support normal-terminal reset at exit
atexit.register(set_normal_term)
t = Thread(target=kb, daemon=True)
t.start()
if __name__ == '__main__':
#StartKB()
pyversion = sys.version_info.major + sys.version_info.minor /10 + sys.version_info.micro / 100
while True:
if keys:
if keys == ['\033'] or keys == ['\\x1b']:
if pyversion > 3.7 and os.name != 'nt':
signal.raise_signal(signal.SIGTERM)
else: sys.exit()
break
print(tuple(keys))
keys.clear()