Python argparse Module – Parse Command-line Arguments Easily

When writing command-line scripts in Python, we might have come across a situation wherein we would need to add more command-line options for our program. Doing the argument parsing by ourselves tend to be very tedious and time-consuming, and often slow us down a lot. Python’s argparse module provides a solution to this problem.

The argparse module provides a way for programmers to write a good command line interfaces quickly and easily. Let us look at how we could use this library to provide good command line interface options to any script that we write.


Python argparse library methods

The library provides us with various methods to parse and deal with the argument string and add user friendly command-line options.

1. Creating the Argument Parser

To process the argument string, we first need to build a parser. The library provides us with argparse.ArgumentParser() to construct an argument parser.

Format: parser = argparse.ArgumentParser(description)

2. Add arguments to the parser object

The next step would be to add arguments / options to the parser for the Command Line Interface (CLI). We do this using parser.add_argument().

Format: parser.add_argument(name, metavar, type, help)

  • name -> name of the attribute of the parser object
  • metavar -> It provides a different name for optional argument in help messages
  • type -> Data type of the variable (could be int, str, etc)
  • help -> The description of the argument in the help message

An example to illustrate the above concepts

import argparse

# Create the parser
parser = argparse.ArgumentParser(description='A Simple Program which prints to the console.')

parser.add_argument('integer', metavar='N', type=int, help='an integer to be printed')

args = parser.parse_args()

a = args.integer
print('Printing the integer')
print(a)

Output

root@Ubuntu $ python argparse_example.py
usage: argparse_example.py [-h] N
argparse_example.py: error: the following arguments are required: N

root@Ubuntu $ python argparse_example.py 10
Printing the integer
10

root@Ubuntu $ python argparse_example.py -h
usage: argparse_example.py [-h] N

A Simple Program which prints to the console.

positional arguments:
  N           an integer to be printed

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

root@Ubuntu $ python argparse_example.py hi
usage: argparse_example.py [-h] N
argparse_example.py: error: argument N: invalid int value: 'hi'

Notice that the module takes care of the type checking of the argument, ensuring that a must be an integer, and that proper arguments must be passed for the program to work. This is the significance of the type parameter.


Further options for the program interface

We can add/modify more options to our program, by specifying two more optional parameters when creating the parser object, namely prog and usage.

Format: argparse.ArgumentParser(prog, usage, description)

  • prog -> Specifies the name of the program (is usually sys.argv[0] by default, but can be modified via this parameter.
  • usage -> Specifies the usage format in the help string.
  • prefix_chars -> Specifies the prefix character for optional arguments (is - for Unix systems, and / for Windows)

To put all of this together, let us write some simple code to illustrate this concept, based on the previous snippet.

import argparse

# Create the parser
parser = argparse.ArgumentParser(prog='simple_printer',
                                usage='%(prog)s [options] integer string',
                                description='A Simple Program which prints to the Console',
                                prefix_chars='-')

# Add an integer argument
parser.add_argument('--integer', metavar='N',
                    type=int, help='an integer to be printed')

# Add a second string argument
parser.add_argument('--string', metavar='S',
                    type=str, help='a string to be printed')

# Parse the list of arguments into an object
# called 'args'
args = parser.parse_args()

print('Argument Object:', args)
print('Type of the Argument Object:', type(args))

first_argument = args.integer
second_argument = args.string

print('Printing the integer')
print(first_argument)

print('Printing the string')
print(second_argument)

1. Passing Optional Arguments

Notice that we have changed the name of the arguments to be --integer and --string. This is because this is the standard format for specifying optional arguments to Python scripts. (python script.py -o --option)

argparse handles this automatically for us, by taking care of the --, ensuring that we only need to type it out once. The below output illustrates the convenience of using argparse for parsing these arguments.

Output for the optional arguments

root@Ubuntu $ python3 argparse_example.py --integer=10
Argument Object: Namespace(integer=10, string=None)
Type of the Argument Object: <class 'argparse.Namespace'>
Printing the integer
10
Printing the string
None

Output for the other cases, showing how argparse takes care of everything for you.

root@Ubuntu $ python3 argparse_example.py 10 Hello
Argument Object: Namespace(integer=10, string='Hello')
Type of the Argument Object: <class 'argparse.Namespace'>
Printing the integer
10
Printing the string
Hello

root@Ubuntu $ python3 argparse_example.py 10
usage: simple_printer [options] --integer --string
simple_printer: error: the following arguments are required: S

root@Ubuntu $ python3 argparse_example.py -h
usage: simple_printer [options] integer string

A Simple Program which prints to the Console

optional arguments:
  -h, --help   show this help message and exit
  --integer N  an integer to be printed
  --string S   a string to be printed

root@Ubuntu $ python3 argparse_example.py --integer 10 --string Hi
Argument Object: Namespace(integer=10, string='Hi')
Type of the Argument Object: <class 'argparse.Namespace'>
Printing the integer
10
Printing the string
Hi

root@Ubuntu $ python3 argparse_example.py --integer=10 --string=Hi
Argument Object: Namespace(integer=10, string='Hi')
Type of the Argument Object: <class 'argparse.Namespace'>
Printing the integer
10
Printing the string
Hi

2. Using short names for optional parameters

To avoid writing the full parameter name for every single optional argument, it is possible to use a single hyphenated option (-o instead of --option) in our script. argparse allows us to do that by simply prepending the short option name as the first parameter when adding an argument to the parser.

Format: parser.add_args('-o', '--option', help='a simple option')

In our previous snippet, we simply add two small changes in the --integer and --string options:

# Add an integer argument
parser.add_argument('-i', '--integer', metavar='N',
                    type=int, help='an integer to be printed')

# Add a second string argument
parser.add_argument('-s', '--string', metavar='S',
                    type=str, help='a string to be printed')

Output when the optional arguments are specified with their short forms:

root@Ubuntu $ python3 argparse_example.py -s=Hi
Argument Object: Namespace(integer=None, string='Hi')
Type of the Argument Object: <class 'argparse.Namespace'>
Printing the Integer
None
Printing the string
Hi

root@Ubuntu $ python3 argparse_example.py -s=Hi -i=10
Argument Object: Namespace(integer=10, string='Hi')
Type of the Argument Object: <class 'argparse.Namespace'>
Printing the integer
10
Printing the string
Hi

Conclusion

In this article, we learned about the basic usage of argparse library for parsing arguments and how to exploit the type checking through the type parameter. We also learned about adding optional arguments to our script and making it more user friendly, using the usage and the hyphenated argument names.

References