getpass --- 可攜式密碼輸入工具

原始碼:Lib/getpass.py


可用性: not WASI.

此模組在 WebAssembly 平台上不起作用或無法使用。更多資訊請參閱 WebAssembly 平台

getpass 模組 (module) 提供了兩個函式:

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).

The echo_char argument controls how user input is displayed while typing. If echo_char is None (default), input remains hidden. Otherwise, echo_char must be a single printable ASCII character and each typed character is replaced by it. For example, echo_char='*' will display asterisks instead of the actual input.

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.

備註

On Unix systems, when echo_char is set, the terminal will be configured to operate in noncanonical mode. Common terminal control characters are supported:

  • 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 版的變更: Added the echo_char parameter for keyboard feedback.

在 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()

回傳使用者的"登入名稱"。

此函式會按順序檢查環境變數 LOGNAMEUSERLNAMEUSERNAME,並回傳其中第一個被設定成非空字串的值。如果均未設定,則在支援 pwd 模組的系統上將會回傳來自密碼資料庫的登入名稱,否則將引發一個 OSError 例外。

大部分情況下,此函式應該要比 os.getlogin() 優先使用。

在 3.13 版的變更: 在過去,除了 OSError 外還會引發各種例外。