如何使用 echo "*" 读取密码在 Python 控制台程序中? [英] How to read password with echo "*" in Python console program?
问题描述
我正在 Windows 下用 Python 编写一个控制台程序.
用户需要登录才能使用该程序,当他输入密码时,我希望他们回显为*",而我可以得到用户输入的内容.
我在标准库中找到了一个名为 getpass 的模块,但是当您输入时它不会回显任何内容(类似 linux).
谢谢.
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.
推荐答案
getpass
模块是用 Python 编写的.你可以很容易地修改它来做到这一点.事实上,这是 getpass.win_getpass()
的修改版本,您可以将其粘贴到您的代码中:
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 == '\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
不过,您可能需要重新考虑这一点.Linux 方式更好;即使只是知道密码中的字符数,对于想要破解密码的人来说也是一个重要的提示.
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.
这篇关于如何使用 echo "*" 读取密码在 Python 控制台程序中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!