How to Use Argparse in Python

The Python argparse module allows you to build a command-line interface for a program. It works by parsing required and optional arguments from a terminal command before putting them into an object which can then be used to create logic.

 

To illustrate what argparse does, let's look at a popular piece of software that has a command-line interface; FFmpeg.

 

fmpeg -i '$video' -vf scale=854:-2 -c:v libx264 -preset veryfast -acodec copy -b:v 800k -b:a 128k -threads 1 '$output'

 

In the above FFmpeg terminal command, there are a bunch of flags, the first of which is an input followed by other optional arguments that describe how the program should run.

 

We can use argparse to build functionality just like FFmpeg's to interpret positional arguments and optional arguments when a program is run from the command-line.

 

Import argparse()

The first step is to import the argparse module at the top of the program.

 

import argparse

 

Create a New ArgumentParser Object & Parse Arguments

Let's write a very basic program that essentially does nothing except create a new ArgumentParser() object and parse the non-existent arguments with parse_args().

 

import argparse
parser = argparse.ArgumentParser()

args = parser.parse_args()

 

note - save the file with an appropriate name and include the extension .py e.g. code.py.

 

Run the Program with the -h Flag

The above program can now be run. Open a new terminal window and cd to the directory where the program is located and run it by typing python followed by the name of the file followed by a -h (help flag).

 

python code.py -h
usage: code.py [-h] echo

positional arguments:

optional arguments:
  -h, --help  show this help message and exit

 

Add Positional Arguments

Positional arguments are required arguments that must be entered in the terminal command. The input argument can be a string, float, integer or file.

 

To add a positional argument use the add_argument() method on the ArgumentParser() object, passing its name inside the () (parenthsis).

 

parser.add_argument('echo')

 

note - the use add_argument before parse_args().

 

import argparse
parser = argparse.ArgumentParser()

parser.add_argument('echo')

args = parser.parse_args()

 

Now when the program is run from the terminal we will see that echo is set as a positional argument.

 

python code.py -h
usage: code.py [-h] echo

positional arguments:
  echo

optional arguments:
  -h, --help  show this help message and exit

 

Get and Return Data from an Argument

Let's expand on our simple program so that it returns the string that the user typed as the echo argument. We can do this by accessing the echo property on the parse_args() object.

 

import argparse
parser = argparse.ArgumentParser()

parser.add_argument('echo', help='return the string you type')

args = parser.parse_args()

print(args.echo)
python code.py hello
hello

 

Add Argument Help Text

To provide some more information about what the argument does we can pass another parameter in the add_argument() method called help=.

 

parser.add_argument('echo', help='return the string you type')

 

Now when the program is run with the -h flag it will provide a detailed description of what each argument does.

 

python code.py -h
usage: code.py [-h] echo

positional arguments:
  echo        return the string you type

optional arguments:
  -h, --help  show this help message and exit

 

Change the Argument Type from String

By default argparse will assume that all arguments are strings. If the input is an integer, we can pass an argument into the add_argument() method with the value type=int.

 

Let's create a program that will multiply a number by itself and return the answer to demonstrate changing the argument type to int.

 

import argparse
parser = argparse.ArgumentParser()

parser.add_argument('multiply', type=int, help='Multiply a number by itself')

args = parser.parse_args()

n = args.multiply
answer = n * n

print(answer)
python code.py 6
36

 

Here are the argument types available:

  • str - string
  • float - floating-point number
  • int - an integer
  • file - a file

 

All The add_argument() Parameters

Here are all the parameters available on the add_arguments() method for reference.

 

add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]
"-v", "--verbosity", action="count", nargs=4, const=str, default=0, type=int, choices=range(1, 10), required=True, help=str, metavar=str, dest='name'

 

  • name or flags - name or a list of option strings
  • action - the type of action this argument will take
  • nargs - the number of command-line arguments that should be consumed
  • const - a constant value required by some action and nargs selections
  • default - the value produced if the argument is absent from the command line
  • type - the type to which the command-line argument should be converted
  • choices - the allowable values for the argument
  • required - make the argument optional or required (only works on optional arguments)
  • help - description of what the argument does
  • metavar - the name for the argument in usage messages
  • dest - the name of the property to use when parse_args() is called

 

Add an Optional Argument

Let's say we wanted to create an optional verbose mode for the program. We could do this by adding an optional argument that listens for the -v or --verbose flag in the terminal command.

 

import argparse
parser = argparse.ArgumentParser()

parser.add_argument('multiply', type=int, help='Multiply a number by itself')
parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity")

args = parser.parse_args()

n = args.multiply
answer = n * n

if args.verbose:
        print(f'The answer to {m} multiplied by {m} is {answer}')
else:
        print(answer)
python code.py 3 -v
The answer to 3 multiplied by 3 is 9
python code.py 3
9

 

An optional argument begins with a - (dash) in shorthand form and -- (two dashes) in the standard format.

 

We are also adding action="store_true" to assign the value True to args.verbose. Not specifying it implies False. Then we just have some logic in the program to do something if the -v argument has been passed in the command-line.

 

Adding More Position Arguments to Work with Multiple Inputs

It is possible to have as many positional arguments as needed with argparse. This is done by adding a new add_argument() method with appropriate parameters. Let's create another program that will take two integer positional arguments and multiply them together.

 

import argparse
parser = argparse.ArgumentParser()

parser.add_argument('first', type=int, help='First number to Multiply')
parser.add_argument('second', type=int, help='Second number to multiply')
parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity")

args = parser.parse_args()

f = args.first
s = args.second
answer = f * s

if args.verbose:
        print(f'The answer to {f} multiplied by {s} is {answer}')
else:
        print(answer)

 

When running the program with the -h flag we can see that two positional arguments are required, first and second.

 

python code.py -h
usage: code.py [-h] [-v] first second

positional arguments:
  first          First number to Multiply
  second         Second number to multiply

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity

 

And when two integers are passed in, we get the result of them multiplied together:

 

python code.py 7 8
56

 

Add Conflicting Options

Let's say we wanted to add two options that could conflict with one another, a --quiet and --verbose mode. We could make this work by adding them as a group using the add_mutually_exclusive_group() method to ensure that only one of the arguments in the mutually exclusive group is present.

 

import argparse

parser = argparse.ArgumentParser()

group = parser.add_mutually_exclusive_group()

group.add_argument('-v', '--verbose', action='store_true')

group.add_argument('-q', '--quiet', action='store_true')  

args = parser.parse_args()

if args.quiet:
        print('Running in quiet mode')
elif args.verbose:
        print('Running is verbose mode')
python prog.py -h
usage: prog.py [-h] [-v | -q]

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose
  -q, --quiet

 

Now the usage is [-v | -q] – only -v or -q is allowed but not both at the same time.

 

Conclusion

You now have an understanding of how to use Python argparse to create a command-line interface for a program.

terminal interface

Related Tutorials

 thumbnail

How to use Sets in Python

September 15, 2020