-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathkeygrabber.py
More file actions
48 lines (37 loc) · 1015 Bytes
/
Copy pathkeygrabber.py
File metadata and controls
48 lines (37 loc) · 1015 Bytes
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
"""
KeyGrabber
Reads key by key keyboard input from the commandline.
Call read to get a list of characters typed.
Restores terminal settings on program exit.
"""
import atexit
import sys
import termios
import tty
class KeyGrabber:
def __init__(self):
self._setup_keys()
atexit.register(self._restore_keys)
def _setup_keys(self):
fd = sys.stdin.fileno()
self.old_settings = termios.tcgetattr(fd)
tty.setcbreak(fd)
new_settings = termios.tcgetattr(fd)
new_settings[6][termios.VMIN] = 0
new_settings[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSADRAIN, new_settings)
def _restore_keys(self):
termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, self.old_settings)
def read(self):
chars = []
while c := sys.stdin.read(1):
chars.append(c)
return chars
if __name__ == "__main__":
import time
kg = KeyGrabber()
while 1:
chars = kg.read()
if chars:
print(f"Got {len(chars)} chars: ", chars)
time.sleep(0.02)