python登录界面实现密码在明文与星号间切换,如何让密码回显为星号

I am trying to figure out how to prompt for a password, and have the users input echoed back as asterisks (********)

So recently, I took on the project of creating a remote server that could be connected to using the socket module in Python. It's not yet done, as I am in the process of making the console used to connect to the server.

I am trying make a login window where a user is prompted to enter their Username and Password, although when the password is entered I am looking for asterisks to be printed, like common password entry (i.e. - Sekr3t is echo'd as: * * * * * *).

After days of research on it, I am nearly done yet there is still a last error that is driving me insane (I am completely unable to solve it). Note - I know there is a getpass module that could be used to replace this, with much greater ease, but nothing echo'd isn't exactly what I'm looking for.

Here's the password login code I have so far, and I cannot figure out why it does not echo asterisks:

import msvcrt

import sys

def login(prompt = '> '):

write = sys.stdout.write

for x in prompt:

msvcrt.putch(x)

passw = ""

while 1:

x = msvcrt.getch()

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

break

if x == '\b':

# position of my error

passw = passw[:-1]

else:

write('*')

passw = passw + x

msvcrt.putch('\r')

msvcrt.putch('\n')

return passw

>

If you read through the code and/or ran it through something like IDLE, you might notice that when the user back-space's, the stored data is erased by one character, but the asterisks printed aren't. i.e. - Sekr3t + backspace = Sekr3, yet * * * * * * is left echo'd. Any help on how to erase the last asterisk when backspace is enter'd would be greatly appreciated. Also note, a lot of this code was from the getpass module. I know it's not that great of an explanation, and probably not that great of code but I'm still learning -- please bear with me.

解决方案

You should be able to erase an asterisk by writing the characters \x08 \x08. The \x08 will move the cursor back one position, the space will overwrite the asterisk, then the last \x08 will move the cursor back again, putting it in the correct position to write the next *.

I don't know off the top of my head how to determine when a backspace is typed, but you can do that easily: just add something like print repr(x) after you've called x = msvcrt.getch(), then start your program and hit backspace.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值