How to Create a Python CLI Tool?

Estimated read time 2 min read

To create a Python CLI tool, you can use the argparse module in Python. Here’s an example:

import argparse

def add_numbers(args):
    result = args.numbers[0]
    for num in args.numbers[1:]:
        result += num
    print(result)

parser = argparse.ArgumentParser(description="Add a list of numbers")
parser.add_argument("numbers", metavar="N", type=int, nargs="+",
                    help="a list of numbers to add")

args = parser.parse_args()

add_numbers(args)

In this example, we define a function add_numbers() that takes a list of numbers and adds them together, then prints the result to the console.

We create an ArgumentParser object from the argparse module with a description of the tool and an argument for the list of numbers to add. The metavar parameter specifies the name of the argument in the usage message, the type parameter specifies the type of the argument (in this case, an integer), and the nargs parameter specifies that the argument can take one or more values.

We then use the parse_args() method of the ArgumentParser object to parse the command line arguments and store them in a namespace object. We pass this namespace object to the add_numbers() function to perform the addition and printing of the result.

To use this tool, you would run it from the command line with a list of numbers to add, like this:

python mytool.py 1 2 3 4 5

This would output the result of adding the numbers 1 through 5. You can customize this example to include additional arguments or perform different actions based on the command line input.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply