0

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?

SoosanShin
  • 85
  • 4

2 Answers2

0

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.

Oleh Rybalchenko
  • 6,998
  • 3
  • 22
  • 36
0

In order to read passwords from the user more securely, check out getpass module.

It can be simply imported and used like shown below. But keep in mind that it doesn't show asterik.

import getpass

password = getpass.getpass('Your message')

Return value of sys.stdin.read(1) is entirely depending on the console you are using.

Sreeram TP
  • 11,346
  • 7
  • 54
  • 108