Argparse for Python CLI

Argparse module in python is used to create CLI or Command Line Interfaces. There are other ways also to make CLI but Argparse makes it very easy and user-friendly.

So, let’s start…

First of all you need import the argparse module in your program.

import argparse

ArgumentParser

Now, to use the module we have to create a Parser object.

parser = argparse.ArgumentParser(description="The Best CLI Application")

The ArgumentParser takes several keyword arguments to setup description, other program settings.

Arguments

To accept and define arguments in the program, we have to call the add_argument() method on the parser. The add_argument accepts several options to provide information about the argument like name, default value or type of the value, action etc. The default action is to store the values.

parser.add_argument('-number', action="store", type=int, help="An Integer")
parser.add_argument('--flag', action="store_true", default=False, "True/False Flag")

Parsing

To parse the passed arguments, we can use the parse_args() method. It will convert each command line argument to appropriate type and then do the appropriate action.

args = parser.parse_args()

Program

Save the code as mycli.py.

Now to run the program, use python mycli.py in your python console, depending upon the location of your program file.

λ python mycli.py --help
usage: mycli.py [-h] [--flag] number

The Best CLI Application

positional arguments:
  number      An Integer

optional arguments:
  -h, --help  show this help message and exit
  --flag      True/False Flag

By default, ArgumentParser calculates the usage message from the arguments it contains. This default message can be overridden with the usage= keyword argument:

parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')

The program name is available using the %(prog)s format specifier.

λ python mycli.py --help
usage: PROG [options]

Now, lets try out our simple CLI Program.

λ python mycli.py 5 --f
Namespace(flag=True, number=5)

Here number is positional argument and --flag or --f is optional.

Argparse also handles the shortcut method for arguments, as shown above. We can use --f in place of --flag.

Our program here returned a Namespace object. Namespace is a Simple class used by default by parse_args() to create an object holding attributes and return it.

We can also use the parser.parse_args() to get individual arguments. For example:

args = parse.parse_args()
print(args.flag)
print(args.number)
λ python mycli.py 5 --f
True
5

This completes a brief and simple overview of the Argparse module in python. You can get the detailed information about the module and other options to customize the behaviour of your program in the official Python Documentation.

You can also commet on this post if there is any query or suggestion about the article.

rksh