-
Notifications
You must be signed in to change notification settings - Fork 0
/
input.py
43 lines (34 loc) · 964 Bytes
/
input.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
"""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)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class AlarmException(Exception):
"""Handling alarm exception."""
pass
def alarmHandler(signum, frame):
"""Handling timeouts."""
raise AlarmException
def input_to(getch, timeout=0.1):
"""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