Tell me something! Python command-line arguments
In the last post, we learned to use the Python
input() function to ask users to enter some information. Rather than sequentially prompting a user to enter information, we can have a user enter any relevent information when the program is run.
Asking the user to input values when calling our program from the command line
The command line is a very powerful tool that can be easily accessed on Linux and Mac computers by opening a Terminal. It can also be accessed on Windows machines by installing Cygwin, Git Bash or some other terminal emulator.
We can create Python programs that change their behaviour or output based on values provided by the user when the program is run. In order to do this, we will use the
sys module, which provides us with various system-related functions. We are particularly intersted in
sys.argv (system arguments vector), which we will use to extract inputs provided by the user.
First, save the complete body mass index (BMI) calculation with the code below as the program
import sys weight = float(sys.argv) # in kg height = float(sys.argv) # in meters bmi = weight/height**2 print(bmi)
And here is an example of what it looks like to run the program from the command line, specifying the user’s weight (75 kg) and height (1.75 meters):
$ python bmi_calc.py 75 1.75 24.489795918367346
The program seems to work. A weight of 75 kg and a height of 1.75 meters results in a body mass index (BMI) of 24.489795918367346.
Inspecting our program
After importing the
sys module, we extract the user’s weight using
sys.argv, convert it to a float number, and assign it to the variable
weight. As was the case with the
input() function used in the previous post, the value returned by
sys.argv is a string variable (i.e., text). We therefore need to convert this string variable into a float variable (see the previous post if you need a refresher of what a float variable is).
We then extract the user’s height using
sys.argv, convert it to a float number and assign this value to the variable
You likely already know that Python starts indexing at zero. So why did we use
sys.argv rather than
sys.argv to access the first command line argument value? That is because the first value,
sys.argv, is the program name. So in our case,
sys.argv would be equal to
Our program then calculates the user’s BMI and prints the resulting value to the terminal.
In this post we learned how to use the
argv function from the
sys module to extract information provided by the user to our program. However, as you may have noticed, the printout of the BMI value was rather ugly (i.e., 24.489795918367346) and uninformative. It would be nice to provide the user with a little more information about what is being printed and also be able to format the BMI value so that there are not so many decimal points. In the next post we will introduce the
.format() function to get full control of our print statements.