【问题标题】:Can Getch (or something similar) be made to accept backspaces?可以让 Getch(或类似的东西)接受退格吗?
【发布时间】:2021-02-08 21:56:38
【问题描述】:

我正在使用以下函数 getPass() 来输入安全密码:

def getPass():
    password = ''
    while True:
        x = getch.getch()
        # x = msvcrt.getch().decode("utf-8")
        if x == '\r' or x == '\n':
            break
        print('*', end='', flush=True)
        password += x
    return password

但是,一个问题是退格不被接受,除非作为新字符:

现实生活中的退格是这样显示的:(“|”符号用于参考)

之前:

••••|

之后:

••• |

但是当我执行getpass() 时,它会在控制台中显示如下:

之前: ****|

然后你按退格键,应该变成什么

*** |

其实变成了

****|*

(注意额外的星号)。

也许我应该将解决方案保留为 print('Type your password:\n(Backspace not accepted: Press Enter to redo)) 将用户置于循环中,但这对于 21 世纪的用户来说非常烦人。

【问题讨论】:

  • 如果 x 是退格,那么您的代码应该删除最后一个星号(通过打印实际的退格,然后是空格,然后是另一个退格)并且 not 将 x 附加到密码。
  • @JohnGordon 表示该行:if x == '\r' or x == '\n': break 将替换 \r\n 将被正确替换,并且当“确认密码”字段选中它时,它会在没有退格的情况下有效?
  • 有什么原因你不使用标准的getpass 模块,这一切已经完成了吗?
  • @jasonharper 我实际上使用了 Mostafa Hassan 发布的这个问题的答案。我从未见过未经编辑的 getpass 模块。谢谢!如果您将此作为答案发布,我会支持您作为答案

标签: python python-3.x input backspace getch


【解决方案1】:

我可以使用标准的 getpass() 模块。

from getpass import getpass
def getPass():
    password = getpass.getpass('Enter Your Password\n>>>')
    return password
password = getpass()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    相关资源
    最近更新 更多