Python’s argparse module for command line parsing

To set the stage: what is argparse? It’s a built-in library in Python that allows you to define and parse arguments passed through the command line. This means you can create fancy scripts with options, subcommands, and all sorts of cool stuff without having to write your own parser from scratch (which would be like trying to solve a Rubik’s cube blindfolded).

So how does it work? Let me show you an example:

# Importing the argparse module to handle command line arguments
import argparse

# Creating an ArgumentParser object with a description
parser = argparse.ArgumentParser(description='Process some integers.')

# Adding an argument for the numbers to be passed in, with a metavar, type, nargs, and help
parser.add_argument('numbers', metavar='n', type=int, nargs='+', help='an integer for the accumulator')

# Adding an argument for the sum option, with an action and help
parser.add_argument('--sum', action='store_true', help='calculate sum of numbers')

# Adding an argument for the max option, with an action and help
parser.add_argument('-m', '--max', action='store_true', help='find max number in list')

# Parsing the arguments passed in through the command line and storing them in the args variable
args = parser.parse_args()

# Checking if the sum option was specified
if args.sum:
    # Initializing a variable to store the total sum
    total = 0
    # Looping through the numbers passed in and adding them to the total
    for num in args.numbers:
        total += num
    # Printing the sum of the numbers passed in
    print(f"The sum of {args.numbers} is {total}")

# Checking if the max option was specified
elif args.max:
    # Initializing a variable to store the maximum number
    max_num = None
    # Looping through the numbers passed in
    for num in args.numbers:
        # Checking if the current number is greater than the current maximum number
        if not max_num or num > max_num:
            # Setting the current number as the new maximum number
            max_num = num
    # Printing the maximum number in the list
    print(f"The maximum number in the list is {max_num}")

# If no action was specified, print a message
else:
    print("No action specified")

In this example, we’re using argparse to parse two optional arguments (–sum and -m) that allow us to calculate either the sum or max of a list of numbers. We also have a positional argument ‘numbers’, which is required for both options.

The `add_argument()` function adds an argument to our parser, while the `parse_args()` function parses and returns the arguments passed through the command line (or raises an error if they’re invalid). We can then use conditional statements to perform different actions based on which options were selected.

It may seem overwhelming at first, but once you get the hang of it, it’s super easy and convenient for creating command-line interfaces that are both intuitive and user-friendly.

SICORPS