Build a Command Line Tool (CLI)


Building a Command Line Interface (CLI) Tool in Python

Building a Command Line Interface (CLI) tool in Python is a great way to automate tasks, interact with the system, and provide a flexible interface to users through the terminal or command prompt. Python provides several libraries that make it easy to build CLI tools, such as argparse, click, and optparse. The most commonly used library for creating CLI tools is argparse due to its simplicity and flexibility.

1. Using argparse to Build a Basic CLI Tool

The argparse module is part of the Python standard library and provides a way to handle command-line arguments passed to the script.

Step-by-Step Example

Let's create a simple CLI tool that can perform arithmetic operations (addition, subtraction, multiplication, and division) based on user input.

1. Install Python (if not already installed):

Ensure that Python is installed on your system. You can verify this by running:

python --version
2. Create the CLI Script:

Create a file named calculator.py with the following content:

import argparse

# Define the functions for the arithmetic operations
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "Error! Division by zero."
    return a / b

# Create the parser object
def create_parser():
    parser = argparse.ArgumentParser(description="CLI Calculator Tool")
    
    # Add arguments for the operation and numbers
    parser.add_argument("operation", choices=["add", "subtract", "multiply", "divide"], help="Operation to perform")
    parser.add_argument("num1", type=float, help="First number")
    parser.add_argument("num2", type=float, help="Second number")
    
    return parser

def main():
    # Create the parser and parse the arguments
    parser = create_parser()
    args = parser.parse_args()

    # Perform the operation based on user input
    if args.operation == "add":
        result = add(args.num1, args.num2)
    elif args.operation == "subtract":
        result = subtract(args.num1, args.num2)
    elif args.operation == "multiply":
        result = multiply(args.num1, args.num2)
    elif args.operation == "divide":
        result = divide(args.num1, args.num2)
    
    print(f"The result of {args.operation}ing {args.num1} and {args.num2} is: {result}")

if __name__ == "__main__":
    main()
Explanation:
  • argparse.ArgumentParser: This is the main class that handles the command-line interface. It takes a description argument that describes the tool's purpose.
  • add_argument: Defines the arguments that the user will provide when running the script.
  • operation: Specifies which operation to perform (add, subtract, multiply, or divide).
  • num1 and num2: The two numbers to operate on.
  • Function Definitions: Simple functions that define the arithmetic operations.
  • args: The parsed arguments from the command line. We check the operation and call the corresponding function.
3. Run the CLI Tool:

You can run the tool directly from the command line by navigating to the folder where your calculator.py script is saved and running it like so:

python calculator.py add 10 5

This will output:

The result of adding 10.0 and 5.0 is: 15.0

You can also perform other operations:

python calculator.py subtract 10 5
python calculator.py multiply 10 5
python calculator.py divide 10 5

2. Enhancing the CLI Tool

Now, let's add more features like optional arguments, error handling, and help messages.

Example: Enhanced CLI Tool

import argparse

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "Error! Division by zero."
    return a / b

def create_parser():
    parser = argparse.ArgumentParser(description="Enhanced CLI Calculator Tool")
    
    # Add positional arguments for the operation and numbers
    parser.add_argument("operation", choices=["add", "subtract", "multiply", "divide"], help="The arithmetic operation to perform.")
    parser.add_argument("num1", type=float, help="First number for operation.")
    parser.add_argument("num2", type=float, help="Second number for operation.")
    
    # Add optional argument for showing the result as a float or integer
    parser.add_argument("-i", "--integer", action="store_true", help="Display result as an integer")
    
    return parser

def main():
    # Create the parser and parse the arguments
    parser = create_parser()
    args = parser.parse_args()

    # Perform the operation
    if args.operation == "add":
        result = add(args.num1, args.num2)
    elif args.operation == "subtract":
        result = subtract(args.num1, args.num2)
    elif args.operation == "multiply":
        result = multiply(args.num1, args.num2)
    elif args.operation == "divide":
        result = divide(args.num1, args.num2)

    # Check if user wants integer result
    if args.integer:
        result = int(result)
    
    print(f"The result of {args.operation}ing {args.num1} and {args.num2} is: {result}")

if __name__ == "__main__":
    main()

New Features:

  • -i or --integer flag: If this option is provided, the result will be displayed as an integer (by converting the float to int).
  • Help messages: argparse automatically generates help messages for you. You can use the -h flag to show the help message:
python calculator.py -h

Example Run:

python calculator.py add 10.5 5.5
The result of adding 10.5 and 5.5 is: 16.0
python calculator.py add 10.5 5.5 -i
The result of adding 10.5 and 5.5 is: 16

3. Packaging the CLI Tool (Optional)

You can make your tool easily accessible and distributable by packaging it as a command-line application. This can be done by creating a setup.py file and defining entry points, but that's beyond the basic CLI setup. However, here's a simple way to call the Python script as a CLI tool after making it executable.

Make the script executable (Linux/Mac):

chmod +x calculator.py

Run it directly from the command line:

./calculator.py add 10 5

4. Conclusion

This is how you can build a basic CLI tool in Python using the argparse library. You can:

  • Define required and optional arguments.
  • Perform different operations based on the user's input.
  • Customize the output and include flags for additional options.