Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

windows - How to read password with echo "*" in Python console program?

I'm writing a console program with Python under Windows.
The user need to login to use the program, when he input his password, I'd like they to be echoed as "*", while I can get what the user input.
I found in the standard library a module called getpass, but it will not echo anything when you input(linux like).
Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The getpass module is written in Python. You could easily modify it to do this. In fact, here is a modified version of getpass.win_getpass() that you could just paste into your code:

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 == '
' or c == '
':
            break
        if c == '03':
            raise KeyboardInterrupt
        if c == '':
            pw = pw[:-1]
            msvcrt.putch('')
        else:
            pw = pw + c
            msvcrt.putch("*")
    msvcrt.putch('
')
    msvcrt.putch('
')
    return pw

You might want to reconsider this, however. The Linux way is better; even just knowing the number of characters in a password is a significant hint to someone who wants to crack it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...