On this page
getpass
Prev: getopt | Up: stdlib_module | Next: gettext
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — getpass
Tags: #public #python3 #stdlib
Import
import getpass
Overview
Prompts for passwords or secrets interactively on a terminal without echoing typed characters (getpass.getpass), and resolves the current OS username (getpass.getuser). Always use getpass.getpass() instead of input() whenever prompting for tokens, passphrases, or passwords.
Quick Start
import getpass
user = getpass.getuser()
assert isinstance(user, str) and len(user) > 0
# Interactive prompt (no echo):
# secret = getpass.getpass("API token: ")
Implementation Walkthrough
1. Safe Token Acquisition (Env Var → Interactive Prompt Fallback)
import getpass
import os
import sys
def get_api_token(env_var: str = "API_TOKEN") -> str:
if token := os.getenv(env_var):
return token
if not sys.stdin.isatty():
raise RuntimeError(f"{env_var} is not set and stdin is not interactive")
return getpass.getpass(f"Enter {env_var}: ")
Gotchas & Boundaries
- Falls back with
GetPassWarningif no controlling terminal is available: Checksys.stdin.isatty()in scripts so CI pipelines fail fast instead of hanging or echoing. getpass.getuser()checks environment variables (LOGNAME,USER,LNAME,USERNAME) beforepwd: Never rely on it for security authorization.
Common Functions
- getpass.getpass() —
getpass(prompt='Password: ', stream=None, *, echo_char=None)— Prompt for a password, with echo turned off. - getpass.getuser() —
getuser()— Get the username from the environment or password database.
Classes & Objects
- getpass.GetPassWarning —
getpass.GetPassWarningclass. (Methods:.add_note(),.with_traceback())
Linked from
Related notes
- tuts/python3/stdlib_module/getopt Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/gettext Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/getpass/getpass Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/getpass/GetPassWarning Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/getpass/getuser Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/io Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/netrc links to this page; shared tags: #stdlib