-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput.py
More file actions
45 lines (37 loc) · 1.08 KB
/
input.py
File metadata and controls
45 lines (37 loc) · 1.08 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
"""Defining input class."""
import sys
import termios
import tty
import signal
class Get:
"""Class to get input."""
def __call__(self):
"""Defining __call__."""
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
newSettings = termios.tcgetattr(sys.stdin)
newSettings[tty.LFLAG] &= ~termios.ICANON
newSettings[tty.LFLAG] &= ~termios.ECHO
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, newSettings)
return ch
class AlarmException(Exception):
"""Handling alarm exception."""
pass
def alarmHandler(signum, frame):
"""Handling timeouts."""
raise AlarmException
def input_to(getch, timeout=0.05):
"""Taking input from user."""
signal.signal(signal.SIGALRM, alarmHandler)
signal.setitimer(signal.ITIMER_REAL, timeout)
try:
text = getch()
signal.alarm(0)
return text
except AlarmException:
signal.signal(signal.SIGALRM, signal.SIG_IGN)
return None