Convert Figma logo to code with AI

pallets logoclick

Python composable command line interface toolkit

15,652
1,397
15,652
137

Top Related Projects

11,854

The pytest framework makes it easy to write small tests, yet scales to support complex functional testing

7,943

Create *beautiful* command-line interfaces with Python

15,584

Typer, build great CLIs. Easy to code. Based on Python type hints.

Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.

37,918

A Commander for modern Go CLI interactions

3,493

CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser

Quick Overview

Click is a Python package for creating beautiful command-line interfaces with as little code as possible. It allows developers to build interactive and user-friendly command-line tools with minimal effort, making it a popular choice for building command-line applications in the Python ecosystem.

Pros

  • Simplicity: Click provides a straightforward and intuitive API for building command-line interfaces, making it easy for developers to get started and create complex applications with minimal code.
  • Flexibility: Click is highly customizable, allowing developers to define command-line options, arguments, and subcommands with ease, and providing a wide range of built-in features to handle various use cases.
  • Cross-platform compatibility: Click-based applications can run on multiple platforms, including Windows, macOS, and Linux, making it a versatile choice for building cross-platform tools.
  • Extensive documentation: The Click project has excellent documentation, including detailed tutorials, examples, and API references, making it easy for developers to learn and use the library effectively.

Cons

  • Limited to Python: Click is a Python-specific library, which means that it may not be the best choice for developers working in other programming languages.
  • Steep learning curve for complex applications: While Click is relatively easy to use for simple command-line tools, building more complex applications with advanced features may require a deeper understanding of the library's internals and best practices.
  • Dependency on Python: Click-based applications are dependent on the Python runtime, which may be a limitation for some users who prefer standalone executables or have specific deployment requirements.
  • Potential performance overhead: Depending on the complexity of the command-line application, the overhead introduced by Click may be a concern for developers working on performance-critical systems.

Code Examples

Here are a few examples of how to use Click to build command-line applications:

  1. Basic Command-line Tool:
import click

@click.command()
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(name):
    """Simple program that greets NAME."""
    click.echo(f'Hello, {name}!')

if __name__ == '__main__':
    hello()

This code creates a simple command-line tool that prompts the user for their name and then greets them.

  1. Command with Arguments and Options:
import click

@click.command()
@click.argument('filename')
@click.option('--count', default=1, help='Number of greetings.')
def hello(filename, count):
    """Reads a file and prints its contents N times."""
    with open(filename, 'r') as f:
        content = f.read()
    for _ in range(count):
        click.echo(content)

if __name__ == '__main__':
    hello()

This example demonstrates how to define command-line arguments and options using Click, allowing the user to specify a file to read and the number of times to print its contents.

  1. Nested Commands:
import click

@click.group()
def cli():
    pass

@cli.command()
def init():
    click.echo('Initializing the project...')

@cli.command()
def build():
    click.echo('Building the project...')

@cli.command()
def deploy():
    click.echo('Deploying the project...')

if __name__ == '__main__':
    cli()

This example demonstrates how to create a command-line interface with nested commands, allowing the user to execute different actions (init, build, deploy) from a single entry point.

Getting Started

To get started with Click, you can install it using pip:

pip install click

Once you have Click installed, you can start building your command-line applications. The basic structure of a Click-based application involves defining commands, options, and arguments using decorators, and then calling the click.command() function to create the entry point for your application.

Here's a simple example to get you started:

import click

@click.command()
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(name):
    """Simple program that greets NAME."""
    click.echo(f'Hello, {name}!')

if __name__ == '__main__

Competitor Comparisons

11,854

The pytest framework makes it easy to write small tests, yet scales to support complex functional testing

Pros of pytest

  • pytest provides a comprehensive and flexible testing framework, allowing for the creation of complex test suites with minimal boilerplate code.
  • The pytest ecosystem includes a wide range of plugins and extensions, making it highly extensible and adaptable to various testing needs.
  • pytest's assertion-based approach to testing, with its powerful assertion rewriting capabilities, makes it easier to write and understand test cases.

Cons of pytest

  • pytest has a steeper learning curve compared to Click, especially for developers who are new to testing or are used to more traditional unit testing frameworks.
  • The flexibility and extensibility of pytest can also make it more complex to configure and set up, especially for larger projects.

Code Comparison

Click:

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo(f"Hello, {name}!")

if __name__ == '__main__':
    hello()

pytest:

import pytest

def test_add():
    assert 2 + 2 == 4

@pytest.mark.parametrize("a,b,expected", [(1, 1, 2), (2, 2, 4), (3, 3, 6)])
def test_add_parametrized(a, b, expected):
    assert a + b == expected
7,943

Create *beautiful* command-line interfaces with Python

Pros of docopt/docopt

  • Declarative Approach: docopt uses a declarative approach to define the command-line interface, which can be more concise and easier to maintain compared to the more imperative approach of Click.
  • Automatic Argument Parsing: docopt automatically parses the command-line arguments based on the defined interface, reducing the amount of boilerplate code required.
  • Flexibility: docopt allows for more flexible command-line argument definitions, including support for subcommands and nested options.

Cons of docopt/docopt

  • Steeper Learning Curve: The declarative nature of docopt's interface definition can be more complex to learn and understand, especially for developers familiar with more traditional imperative approaches.
  • Limited Ecosystem: Click has a larger and more active ecosystem, with a wider range of third-party extensions and plugins available, compared to the more niche docopt.
  • Maintenance Concerns: The docopt project has seen less active maintenance and development in recent years, which could be a concern for long-term projects.

Code Comparison

Click:

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo(f"Hello {name}!")

docopt:

"""Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <name> <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py -h | --help
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.
"""
from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__, version='Naval Fate 2.0')
    print(arguments)
15,584

Typer, build great CLIs. Easy to code. Based on Python type hints.

Pros of Typer

  • Typer provides a more modern and intuitive API for building command-line interfaces, with a focus on type annotations and automatic argument parsing.
  • Typer integrates well with FastAPI, allowing you to easily create CLI tools that complement your web applications.
  • Typer's automatic documentation generation and support for various output formats (e.g., JSON, YAML) make it easier to create user-friendly CLIs.

Cons of Typer

  • Typer is a relatively new library, so it may have a smaller community and fewer resources available compared to Click.
  • Typer's dependency on FastAPI may be a drawback if you don't need the full functionality of the FastAPI framework.
  • Typer's focus on type annotations may be a barrier for developers who are more comfortable with traditional argument parsing approaches.

Code Comparison

Click:

import click

@click.command()
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(name):
    """Simple program that greets NAME."""
    click.echo(f'Hello, {name}!')

if __name__ == '__main__':
    hello()

Typer:

import typer

app = typer.Typer()

@app.command()
def hello(name: str):
    """Simple program that greets NAME."""
    typer.echo(f'Hello, {name}!')

if __name__ == "__main__":
    app()

Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.

Pros of python-fire

  • Automatic CLI Generation: python-fire can automatically generate a command-line interface (CLI) from a Python function, making it easier to create command-line tools.
  • Flexibility: python-fire allows for flexible command-line argument parsing, including support for flags, options, and positional arguments.
  • Minimal Setup: python-fire requires minimal setup and configuration, making it a lightweight option for creating CLI tools.

Cons of python-fire

  • Limited Customization: Compared to Click, python-fire may have less flexibility in terms of customizing the CLI behavior and appearance.
  • Dependency on Google: As a Google-maintained project, python-fire may be less community-driven than Click, which is part of the Pallets project.
  • Potential Performance Impact: The automatic CLI generation in python-fire may have a slight performance impact compared to a more manual approach like Click.

Code Comparison

Click:

import click

@click.command()
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(name):
    """Simple program that greets NAME."""
    click.echo(f'Hello, {name}!')

if __name__ == '__main__':
    hello()

python-fire:

import fire

def hello(name):
    """Simple program that greets NAME."""
    print(f'Hello, {name}!')

if __name__ == '__main__':
    fire.Fire(hello)
37,918

A Commander for modern Go CLI interactions

Pros of Cobra

  • Cobra provides a more comprehensive set of features for building command-line interfaces, including support for subcommands, flags, and environment variables.
  • Cobra has a larger and more active community, with more third-party libraries and integrations available.
  • Cobra's documentation is generally more extensive and easier to navigate than Click's.

Cons of Cobra

  • Cobra has a steeper learning curve than Click, especially for developers who are new to building command-line interfaces.
  • Cobra's codebase is larger and more complex than Click's, which may make it more difficult to customize or extend.
  • Cobra's dependency on the Go programming language may be a drawback for developers who prefer to work in Python.

Code Comparison

Click:

import click

@click.command()
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(name):
    """Simple program that greets NAME."""
    click.echo(f'Hello, {name}!')

if __name__ == '__main__':
    hello()

Cobra:

package main

import (
    "fmt"
    "github.com/spf13/cobra"
)

func main() {
    rootCmd := &cobra.Command{
        Use:   "hello",
        Short: "A simple program that greets the user",
        Run: func(cmd *cobra.Command, args []string) {
            name, _ := cmd.Flags().GetString("name")
            fmt.Printf("Hello, %s!\n", name)
        },
    }

    rootCmd.Flags().StringP("name", "n", "", "The person to greet")
    rootCmd.Execute()
}
3,493

CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser

Pros of Kingpin

  • Kingpin provides a more concise and expressive syntax for defining command-line interfaces, with support for subcommands, flags, and arguments.
  • Kingpin has a more flexible and customizable approach to parsing and validating user input, allowing for more complex command-line interfaces.
  • Kingpin has a smaller codebase and dependencies, which can be beneficial for projects with limited resources.

Cons of Kingpin

  • Kingpin has a smaller community and ecosystem compared to Click, which may mean fewer available resources and third-party packages.
  • Kingpin's documentation and examples may not be as comprehensive as Click's, making it more challenging for new users to get started.
  • Kingpin may not have the same level of maturity and stability as Click, which has been actively developed and used for a longer period.

Code Comparison

Click:

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo(f"Hello {name}!")

if __name__ == '__main__':
    hello()

Kingpin:

package main

import (
    "fmt"
    "github.com/alecthomas/kingpin"
)

func main() {
    app := kingpin.New("hello", "A simple greeting program.")
    count := app.Flag("count", "Number of greetings.").Default("1").Int()
    name := app.Flag("name", "The person to greet.").Required().String()
    kingpin.MustParse(app.Parse(os.Args[1:]))
    for i := 0; i < *count; i++ {
        fmt.Printf("Hello %s!\n", *name)
    }
}

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

$ click_

Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It's the "Command Line Interface Creation Kit". It's highly configurable but comes with sensible defaults out of the box.

It aims to make the process of writing command line tools quick and fun while also preventing any frustration caused by the inability to implement an intended CLI API.

Click in three points:

  • Arbitrary nesting of commands
  • Automatic help page generation
  • Supports lazy loading of subcommands at runtime

A Simple Example

import click

@click.command()
@click.option("--count", default=1, help="Number of greetings.")
@click.option("--name", prompt="Your name", help="The person to greet.")
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for _ in range(count):
        click.echo(f"Hello, {name}!")

if __name__ == '__main__':
    hello()
$ python hello.py --count=3
Your name: Click
Hello, Click!
Hello, Click!
Hello, Click!

Donate

The Pallets organization develops and supports Click and other popular packages. In order to grow the community of contributors and users, and allow the maintainers to devote more time to the projects, please donate today.