-
Notifications
You must be signed in to change notification settings - Fork 0
/
getch.py
executable file
·74 lines (59 loc) · 1.31 KB
/
getch.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
"""This module provides a cross platform implementation of getch."""
import sys
try:
import msvcrt
except ImportError:
try:
import termios
import tty
except ImportError:
pass
__all__ = ('getch',)
def getch(prompt=''):
"""Reads a character from standard input.
If the user enters a newline, an empty string is returned. For the most
part, this behaves just like input(). An optional prompt can be
provided.
"""
print(prompt, end='')
sys.stdout.flush()
# Windows
try:
char = msvcrt.getwch()
except NameError:
pass
else:
if char == '\r' or char == '\n':
char = ''
print(char, end='')
sys.stdout.flush()
return char
# Unix
file_number = sys.stdin.fileno()
try:
old_settings = termios.tcgetattr(file_number)
except NameError:
pass
except termios.error:
pass
else:
tty.setcbreak(file_number)
try:
char = chr(27)
if sys.stdin.isatty():
# avoid escape sequences and other undesired characters
while ord(char[0]) in (8, 27, 127):
char = sys.stdin.read(len(sys.stdin.buffer.peek(1)))
else:
char = sys.stdin.read(1)
if char == '\r' or char == '\n':
char = ''
if 'old_settings' in locals():
print(char, end='')
sys.stdout.flush()
finally:
try:
termios.tcsetattr(file_number, termios.TCSADRAIN, old_settings)
except NameError:
pass
return char