import getpass
api_key = getpass.getpass("Enter your API Key: ")
print((f"You entered an API key of length {len(api_key)}"))getpass is a module in Python's standard library for asking for a
password or another secret. getpass.getpass() works like input(),
but in a terminal it turns off echo, so the characters you type do not
appear on the screen. The module also has getpass.getuser(), which
returns the name of the current user. People use it to ask for an API key
or a database password while a script runs, instead of writing the secret
into the code. This page is an online getpass compiler: the code runs in
your browser, so you can try it without installing anything.
Run the example first, then paste any snippet below into a new cell to try it.
getpass.getpass("Enter your API Key: ") shows the prompt and returns
what you type as a string. On this page it opens a browser dialog, the
same one that input() uses, and the code waits until
you click OK or Cancel. The key is stored in the api_key variable, not
in the code, so it is not part of the notebook when you save or share
it. The example prints only len(api_key), which confirms that a key
arrived without showing it.
To set a password, ask twice and compare the answers. This loop also rejects passwords shorter than 8 characters:
import getpass
while True:
password = getpass.getpass("New password: ")
if len(password) < 8:
print("Use at least 8 characters.")
continue
if password == getpass.getpass("Repeat the password: "):
break
print("The passwords do not match. Try again.")
print("Password set,", len(password), "characters long")
Libraries such as OpenAI read their key from an environment variable when you do not pass one. This common notebook pattern asks only while the variable is missing or empty, so running the cell a second time does not ask again:
import getpass
import os
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API key: ").strip()
key = os.environ["OPENAI_API_KEY"]
print("Key set:", "*" * (len(key) - 4) + key[-4:])
strip() removes spaces or a line break that come along when you paste.
The last line shows only the final four characters. The variable lasts
until you reload the page.
getpass.getuser() does not ask anything. It checks the environment
variables LOGNAME, USER, LNAME and USERNAME in that order and
returns the first one that is set:
import getpass
import os
print(getpass.getuser())
for name in ("LOGNAME", "USER", "LNAME", "USERNAME"):
print(name, os.environ.get(name))
In the browser nobody is logged in, so the result is web_user, a
placeholder name that the Python runtime sets.
getpass()
in a terminal. Avoid typing a secret while you share your screen."" before you
use the value.getpass() cannot turn
off echo. It prints GetPassWarning: Can not control echo on the terminal. and Warning: Password input may be echoed., then reads the
input with the characters visible.