1

Is it possible to hide the message that gets displayed if getpass() cannot hide the message?

GetPassWarning: Can not control echo on the terminal.
Warning: Password input may be echoed.

Is it possible to replace this message with something else more user friendly? If it is, how?

Python
  • 47
  • 8
  • Does this answer your question? [How to use getpass() to hide a users password as it is entered](https://stackoverflow.com/questions/47167139/how-to-use-getpass-to-hide-a-users-password-as-it-is-entered) – Blue Robin Mar 20 '22 at 02:37
  • @BlueRobin , I'm looking for how to hide the warning (if it's possible) and print something more user-friendly. – Python Mar 21 '22 at 23:06
  • Does the answer on the question, answer that though? – Blue Robin Mar 21 '22 at 23:41
  • no... sorry. I'm looking for a way to hide the warning. Even if the thing running the code cannot stop echoing, I want it to print something more user friendly (if it's possible) – Python Mar 23 '22 at 20:20

1 Answers1

1

As far as I know, this message isn't intended to be customizable. Here's a workaround.

Behind the scenes, getpass.getpass is the following function when echo can't be disabled.

def fallback_getpass(prompt='Password: ', stream=None):
    warnings.warn("Can not control echo on the terminal.", GetPassWarning,
                  stacklevel=2)
    if not stream:
        stream = sys.stderr
    print("Warning: Password input may be echoed.", file=stream)
    return _raw_input(prompt, stream)

If you want to customize the message, you could just write your own function that calls getpass._raw_input. For example,

import sys
import getpass

def custom_getpass(prompt='Password: ', stream=None):
    if not stream:
        stream = sys.stderr
    print("This is a custom message to the user.", file=stream)
    return getpass._raw_input(prompt, stream)

You can then call your custom_getpass function directly, or you can replace getpass.getpass with your custom function.

getpass.getpass = custom_getpass

# This prints "This is a custom message to the user." before getting the
# password.
getpass.getpass()

Note that the approach above will always print the custom warning and will always echo the password to the user. If you only want to use the custom function when the fallback getpass is being used, you could do that by simply checking which function getpass is using for getpass.getpass. For example

if getpass.getpass == getpass.fallback_getpass:
    getpass.getpass = custom_getpass

# If echo could not be disabled, then this prints "This is a custom
# message to the user." before getting the password.
getpass.getpass()

Beware this could break without notice in future versions of Python since the workaround relies on the module's "private" functions.

fakedad
  • 1,292
  • 1
  • 10
  • 21