-
Notifications
You must be signed in to change notification settings - Fork 1
/
keypress.py
executable file
·53 lines (37 loc) · 1.02 KB
/
keypress.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
#!/usr/bin/env python3
import sys, select, termios, tty
class keypress:
def __init__(self):
self.old_settings = termios.tcgetattr(sys.stdin)
def available(self):
if self.enabled == 0:
return False
return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
def readkey(self):
if self.available():
return sys.stdin.read(1)
def is_enabled(self):
return self.enabled
def enable(self):
try:
tty.setcbreak(sys.stdin.fileno())
self.enabled = True
except:
print('Failed to enable')
def disable(self):
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
self.enabled = False
if __name__ == '__main__':
import time
kp = keypress()
kp.enable()
i = 0
while 1:
print(i)
i += 1
if kp.available():
c = kp.readkey()
if c == 'q':
break
time.sleep(1)
kp.disable()