Skip to content

#108: Getting Input From the Command Line

When you write scripts you often need to ask the user for an input. Let's look how we can do that in Python.

Prompt the user

We can use the input() function to ask the user for a value and give a hint on what we expect:

var = input("Please enter something: ")
print("You entered: " + var)

If we run this script and enter "Hello", we get this output:

Please enter something: Hello

You entered: Hello

Asking for passwords

When you ask the user for a password you do not want to show it to everyone. Therefore, input() is the wrong method for this kind of input. Instead, we can use the module getpass with a function of the same name that works like input() but hides what the user types:

1
2
3
import getpass
password = getpass.getpass("Please enter your password: ")
print(f"You entered {len(password)} characters")

We can run the code from above and get an output like this:

Please enter your password:

You entered 4 characters

Inside your script you get access to the password but make sure that you do not print it to the command line or a log file!

Conclusion

The two functions input() and getpass() are a great help when you need to ask the user for an input. With the optional arguments you can help the user to enter the data as you need it.