Search code examples
pythonhidegetpass

Is it possible to hide the getpass() warning?


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?


Solution

  • 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.