Understanding Argparse and Command-line arguments

Balakrishnakumar V
4 min readJul 19, 2020
Photo by Clément H on Unsplash

Hey Everyone,

In this post, I will be sharing what is argparse and how to use them in command line arguments.

Before diving in, let’s look into a very simple program in python.

So the function add_and_display has 4 input arguments, a boolean value to control the output display, a description, and two numbers.

If we want to change any of the input arguments, then we manually modify the corresponding values in the code and as the code gets more complex, manipulating these values will become hard.

So one workaround is to use Command-line arguments. They are flags given to a program/script at runtime. They contain additional information for our program so that it can execute.

And a major advantage is that it allows us to give our program different inputs on the fly without actually changing the code.

Luckily to accomplish the above idea, we can make use of the standard python argparse package.

The basic building blocks are listed below.

# Loading the package
import argparse
# Creating an object from the class
parser = argparse.ArgumentParser()
# Adding the command line inputs
parser.add_argument("value1")
# The parse_args() method actually returns some data from the options specified in the previous code, in this case, value1
args = parser.parse_args()

Now let us modify our previous add_and_display example to accept command-line arguments.

add_arguments(parameters):

  • type: Data-type of the variable (str / int / float / strtobool)
  • required: Compulsory variable or not (True / False)
  • help: Some description regarding the variable
  • choices: To include predefined input choices [“add”, “subtract”]
  • default: If variable not present in the input, then it assigns the default value

Our add_and_display function require 4 variables,

  1. number_1 → (type : int, required = True , help =”some description”)
  2. number_2 →(type : int, required = False, help =”some desc”, default=0)
  3. operation → (type : str, required = True, help = “Math Operation”, choices = [“add”, “subtract”])
  4. permission → (type : strtobool, required = True, help = “some desc”, default = False)

Let’s first call these 4 variables using the argparse module, later we join them with our function.

The output of the above code snipped when ran on the terminal,

Just in case if you don’t know which parameters have to be passed in the command line, or say a developer shares his .py file and instructs you to provide the inputs via command-line arguments.

use the below code to get some help about the .py file and it provides the input arguments which needs to be passed.

So now we got some intuition on how to use args-parser. Now let’s join the argparse with our original function.

We can try different sets of inputs for the above code snippet.

1. Providing all arguments:

2. Providing only required arguments:

Since — number_2 is optional, in the below code snippet, I have not included it, and as we expect it’s been filled with the default value 0.

3. Modifying the permissions tag:

Here we set the — permissions to False l, in the below code, as we expect it’s not entering into the function and displays nothing.

4. Not providing the required argument :

In the add_arguments, if we have specified the flag required=True for any variable, then it must be present at the input, otherwise, it will throw an error.

Here in the below code snippet, I am not passing the permissions = True/False argument, which is a required parameter to display the output, and as we expected it throws an error.

Now let’s take a look into 2 types of arguments we can use.

1. Positional Arguments:

They are used when the order of the inputs sent to the function matters. (They are hardly used, but it’s good to know)

2. Optional Arguments:

They are used when the inputs can be sent to the function in any order. (We have been using Optional Arguments so far)

Let’s modify our previous example and add two more numbers as positional arguments.

Now we will use the help function to identify the kind of arguments and later run them in the terminal.

That’s it. Command-line arguments are rudimentary skills, now we know how it works and it’s a no more daunting task.

Want to dig in more?

Refer:

Let me know what you think in the comment section.

Until then, see you next time.

Article By:

BALAKRISHNAKUMAR V

--

--