Building CLI interfaces with Argparse

There are multiple ways to create Command Line Interfaces with Python. But on this page we are going to be looking at using Argparse, the default Python program for creating command line programs.

## Creating a parser

The first step in using the argparse module (aside from importing it) is creating an *ArgumentParser* object:

```
parser = argparse.ArgumentParser(description='Process some integers.')

```

The *ArgumentParser* object will hold all the information necessary to parse the command line into Python data types.

## Adding arguments

Filling an *ArgumentParser*with information about program arguments is done by making calls to the *add\_argument()*method. Generally, these calls tell the *ArgumentParser* how to take the strings on the command line and turn them into objects. This information is stored and used when *parse\_args()* is called.

For example:

```
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max,
                    help='sum the integers (default: find the max)')

```

Later, calling *parse\_args()* will return an object with two attributes, **integers**and **accumulate**. The **integers** attribute will be a list of one or more ints, and the **accumulate** attribute will be either the *sum()* function, if **--sum** was specified at the command line, or the *max()*function if it was not.

### Optional arguments

Optional arguments are proceeded with a dash symbol. The *-h* or *--help* flag is a good example of an optional argument.  An example of building an optional argument for yourself would be something like:

```
parser = argparse.ArgumentParser()

parser.add_argument("-n", "--new", help="Create new list", action="store_true")

```

the action **"store\_true"** is used for storing the value "True", so we can later check if the optional argument has been flagged by the user :

```
# Checking arguments.
if args.new:
    # Run function.
    create_new_list()

```

### Groups

A **group** lets you  make sure that only one of the arguments in the mutually exclusive group is present on the command line at once.

For example:

```
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()

group.add_argument("-n", "--new", help="Create new list", action="store_true")

```

Other types of groups can be made but this mutually exclusive group is particularly useful.

## Parsing arguments

*ArgumentParser* parses arguments through the *parse\_args()*method. This will inspect the command line, convert each argument to the appropriate type and the invoke the appropriate action. In most cases, this means a simple *Namespace* object will be built up from attributes parsed out of the command line:

```
>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

```

In a script, *parse\_args()* will typically be called with no arguments, and the ArgumentParser will automatically determine the command-line arguments from *sys.srgv*.

## References

argparse - Parser for command-line options, arguments and sub-commands

Python Advanced Tutorial 3 - Argparse

Building Beautiful Command Line Interfaces with Python

Python Argparse Cookbook