Python Friday #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.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

Prompt the user

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

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:

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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.