I want to read char one by one and show to astrix *
.
Characters can be showed as *
, but I cannot exit by pushing Enter.
This is my code:
import sys, tty, termios
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
sys.stdout.write('*')
except:
print "ex"
finally:
termios.tcsetattr(fd, termios.TCSADRAIN,old_settings)
return ch
If I input Enter where ch = sys.stdin.read(1)
, what is the return value?
You can use getpass.getpass to prompt a user for a password. But note that getpass
module does not show asterisks for unix password prompts.
As for the second part of the question - sys.stdin.read(1)
returns \n
or \r
for Enter input, it depends on a terminal you're using.
And, finally, I made an example how to use your function to read until CR or LF:
while True:', '\n']: break
ch = getch()
if ch in ['\r', '\n']: break
sys.stdout.flush()
If you really need to show asterisks even for unix, that's the way.