Introduction
Command Line Interfaces (CLIs) are a powerful way to interact with Python applications, allowing users to execute various tasks and operations from the terminal. While Python offers several libraries for creating CLIs, click stands out as a popular and user-friendly choice. In this article, we will explore how to create console scripts in a Python project using click and integrate them seamlessly into our project's setup.py file.
Why click?
click is a Python package that simplifies the process of building command line interfaces. It's known for its ease of use, intuitive syntax, and powerful features. click provides decorators to define commands and options, supports complex argument parsing, and generates helpful documentation automatically. When combined with setup.py, it enables us to distribute our CLI application as a Python package, making it easily installable and shareable.
Getting Started
Step 1: Installing the click python package.
It’s generally a good practice to create a separate Python virtual environment for installing the required Python packages to isolate independent project dependencies. Let's create a separate Python virtual environment named env
.
$python -m venv env
Here we create a virtual environment named env
. Next, let's activate the virtual environment and install the required package click
.
$ source env/bin/activate # activates the venv env
(env)$ pip install click # installs click in env
Step 2: Python Directory Structure
Our Python directory structure will be as follows. Under the mypackage
directory we will be having the mycmd
python package and a setup.py
file.
The
mycmd
python package contains themain.py
which is our Python script for the cli definitions.The
setup.py
file consists of the package information and is used to create and install our below package.
Step 3: Define CLI with Multiple Commands
Let's have a look at our below Python script for CLI definitions
import click
@click.group()
def cli():
"""This is the main CLI application."""
click.echo("This is main click application")
@cli.command()
@click.option('--name', default='world', help='Name to greet')
def hello(name):
"""Greet with a hello message."""
click.echo(f"Hello, {name}!")
@cli.command()
@click.option('--name', default='world', help='Name to greet')
def goodbye(name):
"""Greet with a goodbye message."""
click.echo(f"Goodbye, {name}!")
The script defines a Click group called cli
using the @
click.group
()
decorator. This group represents the main CLI application.
cli
Group: Inside the cli
group, two commands are defined: hello
and goodbye
. These commands are defined using the @cli.command()
decorator.
hello
Command: The hello
command is defined with the name
option, which has a default value of 'world' and a help message. This command greets the user with a "Hello" message, and the name
option allows to specify the name to be greeted.
goodbye
Command: The goodbye
command is defined similarly to the hello
command. It also has a name
option with a default value of 'world' and a help message. This command greets the user with a "Goodbye" message.
Step 4: Create setup.py
Now, let's integrate our CLI with multiple commands into the project's setup.py for easy distribution.
from setuptools import setup, find_packages
setup(
include_package_data=True,
name='cmdpackage',
description='A sample mycmd python package',
version='0.0.2',
packages=find_packages(),
entry_points={
'console_scripts': [
'mycmd = mycmd.main:cli'
]
}
)
Here we define the required metadata for our custom Python package. The main parameter present in the setup.py
file that we have to focus on is entry_points
.
entry_points
: This section defines entry points for our package. In this case, it defines a console script entry point:
'console_scripts'
indicates that we are defining a command-line script.'mycmd'
is the name of the command that users will execute on the command line.'mycmd.main:cli'
specifies the Python function that will be called when the script is executed. In this case, it calls thecli
function from themain
module of themycmd
package.
Step 5: Install and Use CLI
To install the CLI as a Python package, navigate to the directory containing setup.py and run
pip install .
Now, let's test and use our CLI. Let's execute the mycmd
command. Let's ensure we execute this command inside our virtual environment.
(env)$ mycmd --help
Output
We get the following command line output. mycmd --help
is a standard way to access documentation and get information about how to use the mycmd
CLI application, including details about available commands and options. It's a useful command for users who want to learn how to interact with the CLI tool.
Next, let's execute the below command:
$mycmd hello --name Samarth
Output
In this output, the "Hello" message is followed by the name "Samarth," which is provided as an argument to the --name
option in our command. The CLI application uses this value to personalize the greeting message.
Next, let's execute the below command:
$mycmd goodbye --name Samarth
Output
Hence in this output, the "Goodbye" message is followed by the name "Samarth," which is provided as an argument to the --name
option in our command. The CLI application uses this value to personalize the farewell message.
Conclusion
From the above article, we learnt how to build CLI applications using python package click
. We also saw how to combine it with setup.py which enables us to distribute our CLI application as a Python package, making it easily installable and shareable. Click and setup.py provides an excellent framework for building and distributing Python CLIs with multiple commands. This approach helps us to create organized and user-friendly interfaces for applications, enhancing usability and maintainability. So, go ahead and start building a powerful CLI with click and multiple commands today!