getpass --- 可移植的密码输入

源代码: Lib/getpass.py


适用范围: not WASI.

此模块在 WebAssembly 平台上无效或不可用。请参阅 WebAssembly 平台 了解详情。

getpass 模块提供了两个函数:

getpass.getpass(prompt='Password: ', stream=None, *, echo_char=None)

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 using the replace error handler if needed. stream defaults to the controlling terminal (/dev/tty) or if that is unavailable to sys.stderr (this argument is ignored on Windows).

echo_char 参数控制在按键时用户输入将如何显示。如果 echo_charNone (默认值),输入将保持隐藏。 在其他情况下,echo_char 必须是一个可打印的 ASCII 字符而每个键入的字符将由它来替换。例如,echo_char='*' 将显示星号而不是实际输入内容。

If echo-free input is unavailable, getpass() falls back to printing a warning message to stream and reading from sys.stdin and issuing a GetPassWarning.

备注

If you call getpass() from within IDLE, the input may be done in the terminal you launched IDLE from rather than the idle window itself.

备注

在 Unix 系统上,当设置了 echo_char 时,终端将被配置为以 非规范模式 运作。 支持通常的终端控制字符:

  • Ctrl+A - Move cursor to beginning of line

  • Ctrl+E - Move cursor to end of line

  • Ctrl+K - Kill (delete) from cursor to end of line

  • Ctrl+U - Kill (delete) entire line

  • Ctrl+W - Erase previous word

  • Ctrl+V - Insert next character literally (quote)

  • Backspace/DEL - Delete character before cursor

These shortcuts work by reading the terminal's configured control character mappings from termios settings.

在 3.14 版本发生变更: 添加了 echo_char 形参用于键盘反馈。

在 3.15 版本发生变更: When using non-empty echo_char on Unix, keyboard shortcuts (including cursor movement and line editing) are now properly handled using the terminal's control character configuration.

exception getpass.GetPassWarning

一个当密码输入可能被回显时发出的 UserWarning 子类。

getpass.getuser()

返回用户的“登录名称”。

此函数会按顺序检查环境变量 LOGNAME, USER, LNAMEUSERNAME,并返回其中第一个被设为非空字符串的值。如果全都未设置,则在支持 pwd 模块的系统上将返回来自密码数据库的登录名,在其他情况下,将会引发 OSError

通常情况下,此函数应优先于 os.getlogin()

在 3.13 版本发生变更: 在之前版本中,除了 OSError 之外还会引发其他多种异常。