Using Python argparse

Posted on October 1, 2022

Python 3.11 introduced a new and improved argument parser in the argparse module. The new argument parser provides several handy features that make it easier to parse command line arguments in Python scripts. In this post, we’ll take a look at how to use Python’s new argument parser.

Background

The argparse module has been around for a while in Python, providing a standard way to handle command line arguments. The old parser was good, but had some annoyances and limitations.

The new parser in Python 3.11 aims to resolve many of those issues and provide a more powerful and flexible interface for parsing arguments. Some of the major improvements include:

  • Support for subcommands
  • Ability to define argument groups
  • More flexible naming and prefixes
  • Better help messages
  • Validation of argument types

Overall, the new parser makes it simpler and more intuitive to build robust command line interfaces in Python.

Basic Usage

Let’s look at a simple example of how to use the new argument parser. We’ll write a Python script that takes an input file, output file, and an optional verbosity flag:

import argparse

parser = argparse.ArgumentParser()

parser.add_argument("input", help="input file")
parser.add_argument("output", help="output file")
parser.add_argument("-v", "--verbose", action="store_true", help="increase verbosity")

args = parser.parse_args()

print(args.input)
print(args.output)
print(args.verbose)

We first create an ArgumentParser object and then add arguments using the add_argument() method. We can specify parameters like help text, default values, and more. The parse_args() method parses the command line and returns an object with the values.

This provides an easy way to access the argument values in a structured way.

Argument Groups

For additional structure, we can now add argument groups:

parser = argparse.ArgumentParser()

input_group = parser.add_argument_group("Input Options")
input_group.add_argument("input", help="input file")

output_group = parser.add_argument_group("Output Options")  
output_group.add_argument("output", help="output file")

other_group = parser.add_argument_group("Other Options")
other_group.add_argument("-v", "--verbose", action="store_true")

This organizes related arguments into named groups in the help text.

Subcommands

One major new feature is the ability to specify subcommands, each with their own arguments:

parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(help="commands")

# A command 
parser_a = subparsers.add_parser("a", help="A help") 
parser_a.add_argument("bar", type=int)

# B command
parser_b = subparsers.add_parser("b", help="B help")
parser_b.add_argument("--baz", choices=["a", "b", "c"])

args = parser.parse_args() 

if args.command == "a":
   print(args.bar)
elif args.command == "b":
   print(args.baz)

We define subcommands “a” and “b”, each with their own set of arguments. The user specifies the subcommand and arguments, which we can access on args.

This is perfect for building CLIs with multiple commands.

Python’s new argparse module provides a robust and user-friendly interface for parsing command line arguments. Some of the major features include argument groups, subcommands, flexible naming, type checking, and auto-generated help. This improves on the older argparse and makes it easy to build powerful command line tools.

The new parser takes care of all the low-level details, allowing developers to focus on their program’s logic and more easily create complex CLIs in Python.

python programming devops