Comparing Python Command Line Interface Tools: Argparse, Click, and Typer

Python has several tools for creating CLIs, each with its own approach and syntax. Three popular choices for parsing command-line arguments and options are argparse, click, and typer.

  • argparse: Requires manual argument parsing setup with verbose syntax.
  • click: Offers a more concise and declarative way to define commands with decorators.
  • typer: Utilizes Python type hints to create a clean and modern CLI interface with minimal boilerplate.

Here’s a comparison of how to create a simple CLI application with a single command that accepts a string argument using argparse, click, and typer.

argparse

# argparse_example.py
import argparse

def main(message):
    print(f"Message: {message}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="A simple CLI with argparse")
    parser.add_argument("message", type=str, help="The message to print")
    args = parser.parse_args()
    main(args.message)

Usage:

python argparse_example.py "Hello, World!"

click

# click_example.py
import click

@click.command()
@click.argument("message")
def main(message):
    print(f"Message: {message}")

if __name__ == "__main__":
    main()

Usage:

python click_example.py "Hello, World!"

typer

# typer_example.py
import typer

def main(message: str):
    print(f"Message: {message}")

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

Usage:

python typer_example.py "Hello, World!"
Open In Colab

Related Posts

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran