python怎么输入密码为星号_如何在python中输入密码,并为用户的每个字符打印一个星号?...

我写了一个模块来大致说明您是如何独立地使用it平台的。#!/usr/bin/python2

def _masked_input_unix(prompt="Password: ", mask="*"):

pw = ""

# save terminal settings

fd = sys.stdin.fileno()

old = termios.tcgetattr(fd)

new = termios.tcgetattr(fd)

# setup 'cbreak' mode

new[3] = new[3] & ~termios.ECHO

new[3] = new[3] & ~termios.ICANON

new[6][termios.VMIN] = '\x01'

new[6][termios.VTIME] = '\x00'

try:

termios.tcsetattr(fd, termios.TCSADRAIN, new)

print prompt,

# Read the password

while True:

c = sys.stdin.read(1)

# submit chars

if c == '\r' or c == '\n':

sys.stdout.write("%s" % (c))

break

# delete chars

elif c == '\b' or c == '\x7f':

if len(pw) > 0:

pw = pw[:-1]

sys.stdout.write("%s" % ('\b \b'))

# password chars

else:

pw += c

sys.stdout.write("%s" % (mask))

finally:

# ensure we reset the terminal

termios.tcsetattr(fd, termios.TCSADRAIN, old)

return pw

def _masked_input_win(prompt="Password: ", mask='*'):

pw = ""

while True:

c = msvcrt.getch()

# submit chars

if c == '\r' or c == '\n':

while msvcrt.kbhit():

msvcrt.getch()

print

break

elif c == '\x03':

raise KeyboardInterrupt

# delete chars

elif c == '\b' or c == '\x7f':

if len(pw) > 0:

pw = pw[:-1]

msvcrt.putch('\b')

msvcrt.putch(' ')

msvcrt.putch('\b')

# password chars

else:

pw += c

msvcrt.putch(mask)

return pw

## initialize windows or posix function pointer

masked_input = None

try:

import msvcrt

masked_input = _masked_input_win

except ImportError:

import sys, termios

masked_input = _masked_input_unix

if __name__ == "__main__":

p = masked_input()

print "Password is:", p

这适用于单字节编码。添加unicode支持是非常重要的。我怀疑unicode不能很好地与Windows上的getpass模块一起工作。(注意:这并不像将所有内容更改为unicode字符串和使用getwch()那么简单)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值