How do I build CLIs with argparse or Typer?

Building command-line interfaces (CLIs) in Python can be efficiently done using libraries like argparse and Typer. Both libraries provide powerful features to create user-friendly command-line tools.

CLI, argparse, Typer, Python, command-line interface, Python CLI, user-friendly commands, programming tools

This content discusses how to create effective CLIs in Python using argparse and Typer. It highlights the ease of use and flexibility these libraries offer for developing command-line functionalities.

# Example using argparse
import argparse

def main():
    parser = argparse.ArgumentParser(description="A simple CLI example using argparse.")
    parser.add_argument("name", type=str, help="Your name")
    parser.add_argument("--greet", action="store_true", help="Greet the user")

    args = parser.parse_args()

    if args.greet:
        print(f"Hello, {args.name}!")
    else:
        print(f"Goodbye, {args.name}.")

if __name__ == "__main__":
    main()
    
# Example using Typer
import typer

def main(name: str, greet: bool = False):
    if greet:
        typer.echo(f"Hello, {name}!")
    else:
        typer.echo(f"Goodbye, {name}.")

if __name__ == "__main__":
    typer.run(main)
    

CLI argparse Typer Python command-line interface Python CLI user-friendly commands programming tools