In Python you can ask the user for input via the input
function.
pwd = input("Password:")
When you run this command locally, here's what it might look like:
>>> pwd = input("Password:")
Password: supersecret
The pwd
variable will contain the string "supersecret", but notice how the command prompt actually shows what the user is typing! That means that somebody who is sitting next to you, or looking at your screen over zoom, also can read your password! That's bad.
getpass
For situations like this one, you may enjoy using the getpass module in Python instead. It has the same functionality but won't display the typed password.
>>> import getpass
>>> pwd = getpass.getpass("give password")
Password:🗝️
No matter what you type, it won't be printed.
Alternatives
The getpass
module comes with Python and is great when you want to keep things lightweight. If you're building a more serious command line app then odds are that you'll likely want to use a tool like Typer instead. We have a course on Typer, if you're interested, but tools like Typer typically have their own way of asking for sensitive inputs.
To copy the Typer docs, here's an example:
import typer
def main(
name: str,
password: str = typer.Option(
..., prompt=True, confirmation_prompt=True, hide_input=True
),
):
typer.echo(f"Hello {name}. Doing something very secure with password.")
typer.echo(f"...just kidding, here it is, very insecure: {password}")
if __name__ == "__main__":
typer.run(main)
No matter what tool you use, please make sure that passwords don't get displayed on screen. Ever.
Back to main.