-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgetch.py
More file actions
62 lines (44 loc) · 1.23 KB
/
getch.py
File metadata and controls
62 lines (44 loc) · 1.23 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from io import StringIO
from sys import stdin
from termios import TCSADRAIN, tcgetattr, tcsetattr
from tty import setraw
def getString(number: int = 1) -> str:
if number > 10 or number < 1:
raise ValueError
fileno = stdin.fileno()
oldSettings = tcgetattr(fileno)
try:
setraw(fileno)
string = stdin.read(number)
finally:
tcsetattr(fileno, TCSADRAIN, oldSettings)
return string
def getChar() -> str:
return getString(1)
def getInput(prompt: str = ""):
stream = StringIO()
print(prompt, end="", flush=True)
while True:
char = getChar()
if char == "\r":
stream.seek(0)
print()
return stream.read()
stream.write(char)
print(char, end="", flush=True)
def getPassword(prompt: str = "", char="*"):
if len(char) > 1:
raise ValueError
stream = StringIO()
print(prompt, end="", flush=True)
while True:
string = getChar()
if string == "\r":
stream.seek(0)
print()
return stream.read()
stream.write(string)
print(char, end="", flush=True)
if __name__ == "__main__":
word = getPassword("Password: ")
print(word)