Click and Python: Build Extensible and Composable CLI Apps

You can use the Click library to quickly provide your Python automation and tooling scripts with an extensible, composable, and user-friendly command-line interface (CLI). Whether you’re a developer, data scientist, DevOps engineer, or someone who often uses Python to automate repetitive tasks, you’ll very much appreciate Click and its unique features.

In the Python ecosystem, you’ll find multiple libraries for creating CLIs, including argparse from the standard library, Typer, and a few others. However, Click offers a robust, mature, intuitive, and feature-rich solution.

In this tutorial, you’ll learn how to:

  • Create command-line interfaces with Click and Python
  • Add arguments, options, and subcommands to your CLI apps
  • Enhance the usage and help pages of your CLI apps with Click
  • Prepare a Click CLI app for installation, use, and distribution

To get the most out of this tutorial, you should have a good understanding of Python programming, including topics such as using decorators. It’ll also be helpful if you’re familiar with using your current operating system’s command line or terminal.

Creating Command-Line Interfaces With Click and Python

The Click library enables you to quickly create robust, feature-rich, and extensible command-line interfaces (CLIs) for your scripts and tools. This library can significantly speed up your development process because it allows you to focus on the application’s logic and leave CLI creation and management to the library itself.

Click is a great alternative to the argparse module, which is the default CLI framework in the Python standard library. Next up, you’ll learn what sets it apart.

Why Use Click for CLI Development

Compared with argparse, Click provides a more flexible and intuitive framework for creating CLI apps that are highly extensible. It allows you to gradually compose your apps without restrictions and with a minimal amount of code. This code will be readable even when your CLI grows and becomes more complex.

Click’s application programming interface (API) is highly intuitive and consistent. The API takes advantage of Python decorators, allowing you to add arguments, options, and subcommands to your CLIs quickly.

Functions are fundamental in Click-based CLIs. You have to write functions that you can then wrap with the appropriate decorators to create arguments, commands, and so on.

Click has several desirable features that you can take advantage of. For example, Click apps:

  • Can be lazily composable without restrictions
  • Follow the Unix command-line conventions
  • Support loading values from environment variables
  • Support custom prompts for input values
  • Handle paths and files out of the box
  • Allow arbitrary nesting of commands, also known as subcommands

You’ll find that Click has many other cool features. For example, Click keeps information about all of your arguments, options, and commands. This way, it can generate usage and help pages for the CLI, which improves the user experience.

When it comes to processing user input, Click has a strong understanding of data types. Because of this feature, the library generates consistent error messages when the user provides the wrong type of input.

Now that you have a general understanding of Click’s most relevant features, it’s time to get your hands dirty and write your first Click app.

How to Install and Set Up Click: Your First CLI App

Unlike argparse, Click doesn’t come in the Python standard library. This means that you need to install Click as a dependency of your CLI project to use the library. You can install Click from PyPI using pip. First, you should create a Python virtual environment to work on. You can do all of that with the following platform-specific commands:

PS> python -m venv venv
PS> venvScriptsactivate
(venv) PS> python -m pip install click
$ python -m venv venv
$ source venv/bin/activate
(venv) $ python -m pip install click

With the first two commands, you create and activate a Python virtual environment called venv in your working directory. Once the environment is active, you install Click using pip.

Great! You’ve installed Click in a fresh virtual environment. Now go ahead and fire up your favorite code editor. Create a new hello.py file and add the following content to it:

# hello.py

import click

@click.command("hello")
@click.version_option("0.1.0", prog_name="hello")
def hello():
    click.echo("Hello, World!")

if __name__ == "__main__":
    hello()

Read the full article at https://realpython.com/python-click/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Related Articles

Open Source Databases

We had a very fun and engaging chat with Matt Yonkovit who is the Chief Experience Officer at Percona, a service provider for open source databases like MySQL, PostgreSQL, MariaDB, and RocksDB. Matt has worked as a database architect for 10 years before transitioning into consulting roles at both MySQL and Sun Microsystems. In total, he’s been working with databases and open source for nearly 25 years.

PyMC Open Source Development

In this episode of Open Source Directions, we were joined by Thomas Wiecki once again who talked about the work being done with PyMC. PyMC3 is a Python package for Bayesian statistical modeling and Probabilistic Machine Learning focusing on advanced Markov chain Monte Carlo (MCMC) and variational inference (VI) algorithms. Its flexibility and extensibility make it applicable to a large suite of problems.

Responses

Your email address will not be published. Required fields are marked *