Drekin / win-unicode-console

A Python package to enable Unicode support when running Python from Windows console.
MIT License
103 stars 12 forks source link

getpass warns that echo free input is not available #24

Closed anthrotype closed 8 years ago

anthrotype commented 8 years ago

when win_unicode_console is enabled, and use getpass.getpass() I get:

C:\Python27\lib\getpass.py:92: GetPassWarning: Can not control echo on the terminal.
  return fallback_getpass(prompt, stream)
Warning: Password input may be echoed.
Password: password

For now I resorted to disabling it immediately before I call getpass and reenabling it afterwards:

def prompt_password():
    if HAS_WIN_UNICODE_CONSOLE:
        win_unicode_console.disable()
    password = getpass.getpass()
    if HAS_WIN_UNICODE_CONSOLE:
        win_unicode_console.enable()
    return password

Do you know any better workaround or fix?

Also, what is the preferred way to check from code if win_unicode_console has been previously enabled? It would be nice if there was a function returning a bool which tells whether win_unicode_console is already enabled or not. My global HAS_WIN_UNICODE_CONSOLE in the code above is True whenever win_unicode_console can be imported, but that doesn't mean it is also enabled. I don't want to re-enable it if it wasn't before running getpass.

Thanks!

Cosimo

Drekin commented 8 years ago

The problem with getpass is the test here: https://hg.python.org/cpython/file/tip/Lib/getpass.py#l100. I'll ask why that test looks like this. A workaround is to temporarily change sys.stdin to the original value:

from contextlib import _RedirectStream
import getpass

class redirect_stdin(_RedirectStream):
    """Context manager for temporarily redirecting stdin to another file."""

    _stream = "stdin"

def prompt_password():
    with redirect_stdin(sys.__stdin__):
        return getpass.getpass()

Note it is not needed to mention win_unicode_console and that is a good thing. Application of win_unicode_console should be transparent and ordinary code shouldn't explicitly mention it. Also, it is not possible to signal whether win_unicode_console is enabled or not since enabling it may apply various fixes depending on Python version, platform version, and an explicit demand. There is no single “enabled” state.

anthrotype commented 8 years ago

Thanks for your reply!