Python 如何在输入密码时将密码转换为星号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35805078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:58:51  来源:igfitidea点击:

How do I convert a password into asterisks while it is being entered?

python

提问by LeroyJD

Is there a way in Python to convert characters as they are being entered by the user to asterisks, like it can be seen on many websites?

Python 中是否有一种方法可以将用户输入的字符转换为星号,就像在许多网站上可以看到的那样?

For example, if an email user was asked to sign in to their account, while typing in their password, it wouldn't appear as characters but rather as *after each individual stroke without any time lag.

例如,如果电子邮件用户被要求登录他们的帐户,在输入他们的密码时,它不会显示为字符,而是显示为*没有任何时间延迟的每个单独的笔划之后。

If the actual password was KermitTheFrog, it would appear as *************when typed in.

如果实际密码为KermitTheFrog,则显示为*************输入时的密码。

回答by pp_

There is getpass(), a function which hidesthe user input.

getpass()一个隐藏用户输入的功能。

import getpass

password = getpass.getpass()
print(password)

回答by Matt

If you're using Tkinter: (this is Python 2.x. However, 3.x would be very similar)

如果您使用的是 Tkinter:(这是 Python 2.x。但是,3.x 将非常相似)

from Tkinter import Entry, Tk

master = Tk()

Password = Entry(master, bd=5, width=20, show="*")
Password.pack()

master.mainloop()

Password entry with tkinter

使用 tkinter 输入密码

In the shell, this is not possible. You can however write a function to store the entered text and report only a string of *'s when called. Kinda like this, which I did not write. I just Googled it.

在 shell 中,这是不可能的。但是,您可以编写一个函数来存储输入的文本,并在调用时仅报告一串 *。 有点像这样,我没有写。我刚刚谷歌了一下。

回答by Tigran Aivazian

You can do this:

你可以这样做:

# if getch module is available, then we implement our own getpass() with asterisks,
# otherwise we just use the plain boring getpass.getpass()
try:
    import getch
    def getpass(prompt):
        """Replacement for getpass.getpass() which prints asterisks for each character typed"""
        print(prompt, end='', flush=True)
        buf = ''
        while True:
            ch = getch.getch()
            if ch == '\n':
                print('')
                break
            else:
                buf += ch
                print('*', end='', flush=True)
        return buf
except ImportError:
    from getpass import getpass

回答by ASHISH KUMAWAT

while using getpassin python, nothing is indicated to show a password input.

getpass在python中使用时,没有指示显示密码输入。

this can be resolved by this simple solution:

这可以通过这个简单的解决方案来解决:

just copy the ‘getpass_ak.py'module provided in the link to python's Lib folder.

只需将‘getpass_ak.py'链接中提供的模块复制到 python 的 Lib 文件夹。

https://starrernet.wixsite.com/analytix/python-coder

https://starrernet.wixsite.com/analytix/python-coder

use the following code:

使用以下代码:

import getpass_ak

a = (getpass_ak.getpass('password: '))

this will add * to your password inputs.

这会将 * 添加到您的密码输入中。

回答by Ahndwoo

For anyone who would actually want to have asterisks appear, here's an improvement on Tigran Aivazian's answer. This version imports the built-in msvcrt.getch, adds cases for different line endings when hitting 'Enter/Return', and includes logic to support Backspace, as well as Ctrl+C (KeyboardInterrupt):

对于任何真正想要出现星号的人来说,这是对Tigran Aivazian 答案的改进。此版本导入内置msvcrt.getch,在点击“Enter/Return”时添加不同行尾的情况,并包含支持 Backspace 和 Ctrl+C(键盘中断)的逻辑:

try:
    from msvcrt import getch
    def getpass(prompt):
        """Replacement for getpass.getpass() which prints asterisks for each character typed"""
        print(prompt, end='', flush=True)
        buf = b''
        while True:
            ch = getch()
            if ch in {b'\n', b'\r', b'\r\n'}:
                print('')
                break
            elif ch == b'\x08': # Backspace
                buf = buf[:-1]
                print(f'\r{(len(prompt)+len(buf)+1)*" "}\r{prompt}{"*" * len(buf)}', end='', flush=True)
            elif ch == b'\x03': # Ctrl+C
                raise KeyboardInterrupt
            else:
                buf += ch
                print('*', end='', flush=True)
        return buf.decode(encoding='utf-8')
except ImportError:
    from getpass import getpass

Please feel free to suggest any other changes, or ways to improve this; I hacked the changes together pretty quickly, especially with the Backspace logic.

请随时提出任何其他更改或改进方法;我很快就修改了这些更改,尤其是使用 Backspace 逻辑。

回答by ?ukasz Rogalski

You may want to check getpassfunction.

您可能想要检查getpass功能。

Prompt the user for a password without echoing. The user is prompted using the string prompt, which defaults to 'Password: '. On Unix, the prompt is written to the file-like object stream. stream defaults to the controlling terminal (/dev/tty) or if that is unavailable to sys.stderr (this argument is ignored on Windows).

提示用户输入密码而不回显。使用字符串提示提示用户,默认为“密码:”。在 Unix 上,提示被写入类文件对象流。流默认为控制终端 (/dev/tty) 或者如果它对 sys.stderr 不可用(此参数在 Windows 上被忽略)。

Note: This module mimics unix password prompts and does not show asterisks.

注意:此模块模拟 unix 密码提示,不显示星号。

Usage:

用法:

import getpass
getpass.getpass()