36. Command Line Interfaces (CLI)

Creating Command Line Interfaces (CLIs) in Python is a common task, and libraries like argparse and click make it easy to build powerful and flexible command-line tools. Here are several code snippets that demonstrate how to use these libraries for building robust CLI tools.


1. Basic CLI with argparse

This is a basic example of how to use argparse to create a command-line tool that accepts arguments.

Copy

import argparse

def main():
    parser = argparse.ArgumentParser(description="A simple CLI tool.")
    parser.add_argument('name', type=str, help="Your name")
    parser.add_argument('age', type=int, help="Your age")

    args = parser.parse_args()
    
    print(f"Hello {args.name}, you are {args.age} years old!")

if __name__ == "__main__":
    main()

2. CLI with Optional Arguments (argparse)

This example demonstrates how to add optional arguments to your CLI tool.

Copy


3. CLI with Default Values (argparse)

You can set default values for your arguments in argparse.

Copy


4. CLI with Subcommands (argparse)

argparse allows you to implement subcommands in your CLI tool.

Copy


5. CLI with Arguments Validation (argparse)

You can add custom validation to your arguments using argparse.

Copy


6. Basic CLI with Click

This is a basic example using the click library to create a CLI tool.

Copy


7. CLI with Options (Click)

This example demonstrates how to add options to your CLI tool with click.

Copy


8. CLI with Default Values and Click

You can also set default values for options in click.

Copy


9. CLI with Complex Subcommands (Click)

click also supports subcommands for more complex CLI tools.

Copy


10. CLI with Custom Validation and Click

Here’s how to implement custom validation logic using click.

Copy


These snippets cover basic and advanced usage of both argparse and click for building command-line tools, providing the flexibility to handle simple to complex arguments, subcommands, validations, and options. You can choose between argparse for a built-in solution or click for a more user-friendly approach with additional features.

Last updated