-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathinput_listener.py
More file actions
41 lines (32 loc) · 1.17 KB
/
input_listener.py
File metadata and controls
41 lines (32 loc) · 1.17 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
# input_listener.py - Non-blocking keyboard input handler
import sys
import termios
import tty
import select
class InputListener:
"""Handles non-blocking keyboard input"""
def __init__(self):
self.old_settings = None
def __enter__(self):
self.old_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
return self
def __exit__(self, type, value, traceback):
if self.old_settings:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
def is_data(self):
return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
def check_for_space(self):
if self.is_data():
c = sys.stdin.read(1)
if c == ' ':
return True
return False
def pause_for_input(self):
"""Restore normal terminal mode for blocking input()"""
if self.old_settings:
# Use TCSADRAIN to wait for output, don't discard input
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
def resume_cbreak(self):
"""Re-enable cbreak mode after input"""
tty.setcbreak(sys.stdin.fileno())