-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_input_example.py
78 lines (73 loc) · 2.16 KB
/
user_input_example.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import sys, tty, termios, select
"""
#blocking. program sleeps while waiting to user input
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setcbreak(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
while True:
ch = getch()
print(ch,end="\n\033[F")
if ch == "q":
print("end")
break
# getch blocking without tty or select modules
def getch_block() -> str:
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
new = old_settings
new[3] &= ~(termios.ICANON | termios.ECHO)
new[6][termios.VMIN] = 1
new[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSADRAIN, new)
try:
#tty.setcbreak(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
"""
#Non blocking a.k.a. busy waiting. useful for when stuff needs to happen without user input
def getch_noblock():
fd = sys.stdin #.fileno();
old_settings = termios.tcgetattr(fd)
#new_settings = termios.tcgetattr(fd)
#new_settings[3] = new_settings[3] & ~termios.ECHO #no echo
try:
tty.setcbreak(fd)
r, _, _ = select.select([fd],[],[],.01) #timeout. smaller = more responsive but more cpu usage
if(r):
ch = sys.stdin.read(1) #TODO: handle special escape chars like ^[ arrow keys
else:
ch = -1
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
while True:
ch = getch_noblock()
print(ch, end="\n\033[F")
if ch == "q":
print("end")
break
#"""
""" # getch no block without select or tty modules
def getch_noblock() -> str: # handle user input. blocking mode
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
new = old_settings
new[3] &= ~termios.ICANON
new[6][termios.VMIN] = 0
new[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSADRAIN, new)
try:
#tty.setcbreak(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
"""