Getting command-line password input in Python

Nacht picture Nacht · Feb 8, 2012 · Viewed 222.9k times · Source

You know how in Linux when you try some Sudo stuff it tells you to enter the password and, as you type, nothing is shown in the terminal window (the password is not shown)?

Is there a way to do that in Python? I'm working on a script that requires so sensitive info and would like for it to be hidden when I'm typing it.

In other words, I want to get the password from the user without showing the password.

Answer

Sven Marnach picture Sven Marnach · Feb 8, 2012

Use getpass.getpass():

from getpass import getpass
password = getpass()

An optional prompt can be passed as parameter; the default is "Password: ".

Note that this function requires a proper terminal, so it can turn off echoing of typed characters – see “GetPassWarning: Can not control echo on the terminal” when running from IDLE for further details.