如何在Python控制台程序中使用echo"*"读取密码?

won*_*ng2 9 python windows

我正在Windows下用Python编写一个控制台程序.
用户需要登录才能使用该程序,当他输入密码时,我希望它们被回显为"*",而我可以得到用户输入的内容.
我在标准库中找到了一个名为getpass的模块,但是当你输入(linux like)时它不会回显任何东西.
谢谢.

kin*_*all 8

getpass模块是用Python编写的.您可以轻松修改它来执行此操作.实际上,这是getpass.win_getpass()您可以粘贴到代码中的修改版本:

import sys

def win_getpass(prompt='Password: ', stream=None):
    """Prompt for password with echo off, using Windows getch()."""
    import msvcrt
    for c in prompt:
        msvcrt.putch(c)
    pw = ""
    while 1:
        c = msvcrt.getch()
        if c == '\r' or c == '\n':
            break
        if c == '\003':
            raise KeyboardInterrupt
        if c == '\b':
            pw = pw[:-1]
            msvcrt.putch('\b')
        else:
            pw = pw + c
            msvcrt.putch("*")
    msvcrt.putch('\r')
    msvcrt.putch('\n')
    return pw
Run Code Online (Sandbox Code Playgroud)

但是,您可能想重新考虑这个问题.Linux方式更好; 即使只知道密码中的字符数也是想要破解它的人的一个重要暗示.


Jos*_*ber 5

kindall的答案很接近,但它有退格的问题,没有删除星号,以及退格能够回到输入提示之外.

尝试:

def win_getpass(prompt='Password: ', stream=None):
    """Prompt for password with echo off, using Windows getch()."""
    if sys.stdin is not sys.__stdin__:
        return fallback_getpass(prompt, stream)
    import msvcrt
    for c in prompt:
        msvcrt.putwch(c)
    pw = ""
    while 1:
        c = msvcrt.getwch()
        if c == '\r' or c == '\n':
            break
        if c == '\003':
            raise KeyboardInterrupt
        if c == '\b':
            if pw == '':
                pass
            else:
                pw = pw[:-1]
                msvcrt.putwch('\b')
                msvcrt.putwch(" ")
                msvcrt.putwch('\b')
        else:
            pw = pw + c
            msvcrt.putwch("*")
    msvcrt.putwch('\r')
    msvcrt.putwch('\n')
    return pw
Run Code Online (Sandbox Code Playgroud)

注意mscvrt.putwch不能与python 2.x一起使用,你需要使用mscvrt.putch.