2

Is there any builtin function that can be used for getting a password in python. I need answer like this

Input: Enter a username: abcdefg Enter a password : ******** If i enter a password abcdefgt. It shows like ********.

4
  • The getpass module prompts for a password with echo off, but doesn't show *****. Commented Aug 9, 2016 at 3:26
  • Is there any option to print * side by side Commented Aug 9, 2016 at 9:21
  • @Dinesh are you on windows or a unix-like platform? Commented Aug 10, 2016 at 2:26
  • I am using unix platform Commented Aug 10, 2016 at 3:18

2 Answers 2

4

Original

There is a function in the standard library module getpass:

>>> import getpass
>>> getpass.getpass("Enter a password: ")
Enter a password: 
'hello'

This function does not echo any characters as you type.

Addendum

If you absolutely must have * echoed while the password is typed, and you are on Windows, then you can do so by butchering the existing getpass.win_getpass to add it. Here is an example (untested):

def starred_win_getpass(prompt='Password: ', stream=None):
    import sys, getpass

    if sys.stdin is not sys.__stdin__:
        return getpass.fallback_getpass(prompt, stream)

    # print the prompt
    import msvcrt
    for c in prompt:
        msvcrt.putwch(c)

    # read the input
    pw = ""
    while 1:
        c = msvcrt.getwch()
        if c == '\r' or c == '\n':
            break
        if c == '\003':
            raise KeyboardInterrupt
        if c == '\b':
            pw = pw[:-1]

            # PATCH: echo the backspace
            msvcrt.putwch(c)         
        else:
            pw = pw + c

            # PATCH: echo a '*'
            msvcrt.putwch('*')         

    msvcrt.putwch('\r')
    msvcrt.putwch('\n')
    return pw

Similarly, on unix, a solution would be to butcher the existing getpass.unix_getpass in a similar fashion (replacing the readline in _raw_input with an appropriate read(1) loop).

Sign up to request clarification or add additional context in comments.

Comments

0

Use the getpass() function and then print the number of stars equivalent to the number of characters in the password. This is a sample:

import getpass
pswd = getpass.getpass('Password:')
print '*' * len(pswd)

The drawback is it does not print ***** side by side.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.