【发布时间】:2015-09-26 00:54:53
【问题描述】:
我想写一个小项目,它需要你输入你的id和passwd,但是我需要一个函数在你输入passwd时用'*'替换passwd,我只知道raw_input()可以输入一些东西,所以我无法解决问题。函数怎么写?
【问题讨论】:
-
@lanAuld,哦,但是我需要在你输入密码时显示“*”而不是仅仅隐藏。
标签: python
我想写一个小项目,它需要你输入你的id和passwd,但是我需要一个函数在你输入passwd时用'*'替换passwd,我只知道raw_input()可以输入一些东西,所以我无法解决问题。函数怎么写?
【问题讨论】:
标签: python
试试这个:
import getpass
pw = getpass.getpass()
【讨论】:
如果一切都失败了,您可以修改 getpass 库(很遗憾,您不能对其进行子类化)。
例如windows的代码(source):
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
import random
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':
pw = pw[:-1]
else:
pw = pw + c
stars = random.randint(1,3)
for i in range(stars):
msvcrt.putwch('*') #<= This line added
msvcrt.putwch('\r')
msvcrt.putwch('\n')
return pw
应该为输入的每个字符打印一个'*'。
编辑:
getpass() 被声明与 Python 2 不兼容,而在 Python 2 上(至少在我的机器上),putwch() 给出了TypeError: must be cannot convert raw buffers, not str。
这可以通过改变来解决:
msvcrt.putwch(c) 到 msvcrt.putwch(unicode(c))
和
msvcrt.putwch('str') 到 msvcrt.putwch(u'str')
如果您不需要处理 unicode,或者只需将 putwch() 替换为 putch()。
编辑2:
我添加了一个随机元素,这样每次按键都会打印 1-3 颗星
【讨论】:
msvcrt.putwch() 也给了我TypeError: must be cannot convert raw buffers, not str。您是否正在使用 Python 2?
msvcrt.putwch() 需要一个 unicode 字符串。在 python 2 你需要做 msvcrt.putwch(u'\r') 而不是 msvcrt.putwch('\r')
我在寻找在接受密码时让 python 打印“*”而不是空格的方法后发现了这篇文章,我发现 SiHa 的答案真的很有帮助,但它并没有删除“ *' 如果我们按退格键已经打印,所以我又遇到了另一个帖子:How to have password echoed as asterisks,组合代码:
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
import random
for c in prompt:
msvcrt.putch(c)
pw = ""
while 1:
c = msvcrt.getwch()
if c == '\r' or c == '\n':
break
elif c == '\003':
raise KeyboardInterrupt
elif c == '\b':
if pw != '': # If password field is empty then doesnt get executed
pw = pw[:-1]
msvcrt.putwch(u'\x08')
msvcrt.putch(' ')
msvcrt.putwch(u'\x08')
else:
pw = pw + c
msvcrt.putch('*') #<= This line added
msvcrt.putch('\r')
msvcrt.putch('\n')
return pw
【讨论】: