Author's image | DALLE-3 and Canva
Sometimes what seems very complex can be made very simple and that is exactly what the library'Click' achieves. It makes building command line applications in Python easy and simple. For example, you can use Click to create a file organizer that classifies files into folders based on their type. Developers use click to automate their daily tasks without getting bogged down in the complexity of syntax and procedures. Not only that, this library also allows integrations with other Python libraries, so you can enhance your applications even further. In short, I can say that Click makes the developer's life much easier.
Why click?
Click is a great choice for creating command line applications in Python because it offers many useful features that other utilities may lack.
- Easy to combine commands: Clicking allows deferred composition of commands without restrictions.
- Follow standard conventions: Supports Unix/POSIX command line conventions.
- Environment variable support: You can load values directly from environment variables.
- Helpful Helpers: Provides common helps such as retrieving direct keyboard input, clearing the screen, getting terminal dimensions, and finding configuration paths.
- Custom Value Request: Easily ask users to contribute when necessary.
- File handling: Built-in support for file management.
- Extensibility: You can easily create custom commands and integrate Click into larger applications, improving adaptability.
Getting started
First, you need to install the library using the following command:
Click offers many advanced features, but let's focus on the fundamental concepts to give you a solid understanding of the library and help you build CLI applications effectively.
1. Commands
@click.command()
is a Click decorator that defines a function in a CLI command, making it executable from the command line. Let's understand it by creating a simple application that prints a goodbye message:
import click
@click.command()
def farewell():
""" Simple program that prints a farewell message. """
click.echo('Goodbye! Take care.')
if __name__ == '__main__':
farewell()
click.echo()
is a utility function that prints the output to the terminal.
You can run the application from your terminal like:
Production:
2. Options
@click.option()
used to add command line options to commands in Click. These options are optional parameters or flags that you can pass to a command to modify its behavior. They usually begin with a double hyphen (–). You can apply data types for these options (e.g., int, float, str), set default values, prompt users for information if the option is not provided, and include help text, which will be displayed when users invoke the option. flag –help . This makes the commands more flexible and easier to use.
Now that you know these basic concepts, it will be easier for you to follow the example that calculates the area of the rectangle:
import click
@click.command()
@click.option('--length', type=float, default=3, prompt="Length of the rectangle")
@click.option('--width', type=float, default=2, prompt="Width of the rectangle")
def area(length, width):
""" Calculate the area of a rectangle. """
if length <= 0 or width <= 0:
click.echo("Length and width must be positive values.")
else:
area = length * width
click.echo(f'The area of the rectangle with length {length} and width {width} is {area}')
if __name__ == '__main__':
area()
In this example,
@click.command()
defines the command area that calculates the area of the rectangle.@click.option()
takes the length and width as user input and ensures it is of type float. Note that the type is string by default and you must specify otherwise. The default values of 3 for length and 2 for width are used if the user does not provide these values via command line flags and also ignores them during the request, that is, by pressing Enter without providing the values.- The length * width formula is used to calculate the area.
- The program checks if the length or width value is negative and displays an error message if necessary.
Run the application
- You can run this application from your terminal as follows:
- Or you can directly provide the length and width values and run it as follows:
python3 rectangle_area.py
You will be prompted to enter the length value. In my case I have given it the value 4.
Length of the rectangle:4
Give the value and press Enter
.
Now, you will be asked to enter the width value. I have given the width value as 11.
Width of the rectangle:11
Press Enter
thereafter.
python3 rectangle_area.py --length 4 --width 11
Production
The area of the rectangle with length 4.0 and width 11.0 is 44.0
3. Multiple Value Options
Multiple value options in Click allow you to pass multiple values to a single option. To do this, set the parameter multiples= True, which is False by default. Let's understand this concept by calculating the area of a rectangle using multiple values:
import click
@click.command()
@click.option('--length', multiple=True, type=float)
@click.option('--width', multiple=True, type=float)
def area(length, width):
""" Calculate the area of multiple rectangles. """
if len(length) != len(width):
click.echo("The number of lengths must match the number of widths.")
return
for l, w in zip(length, width):
if l <= 0 or w <= 0:
click.echo(f"Length {l} and width {w} must be positive values.")
else:
area = l * w
click.echo(f'The area of the rectangle with length {l} and width {w} is {area}')
if __name__ == '__main__':
area()
You can run this application from your terminal as follows:
python3 rectangle_area.py --length 2 –-length 3 --width 3 --width 6
Production
The area of the rectangle with length 2.0 and width 3.0 is 6.0
The area of the rectangle with length 3.0 and width 6.0 is 18.0
4. Arguments
In Click, arguments are positional parameters that you must supply in the order specified by the command. Unlike options, which are specified using flags (such as –name), arguments are required and do not use double dashes (–). Additionally, you cannot set default values for arguments or prompt them from the user; They must be provided directly when the command is executed.
import click
@click.command()
@click.argument('length', type=float)
@click.argument('width', type=float)
def area(length, width):
""" Calculate the area of a rectangle. """
if length <= 0 or width <= 0:
click.echo("Length and width must be positive values.")
else:
area = length * width
click.echo(f'The area of the rectangle with length {length} and width {width} is {area}')
if __name__ == '__main__':
area()
To run this application, provide the length and width arguments directly on the command line:
python3 rectangle_area.py 5 10
Production
The area of the rectangle with length 5.0 and width 10.0 is 50.0
5. Group commands
In Click, you can group related commands using @click.group()
. This creates a CLI application with multiple subcommands, making it easy to manage and organize multiple functions under one group of commands. Let's explore this with the help of an example:
import click
@click.group()
def rectangle():
""" Commands for rectangle calculations. """
pass
@click.command()
@click.option('--length', prompt="Length of the rectangle", type=float)
@click.option('--width', prompt="Width of the rectangle", type=float)
def area(length, width):
""" Calculate the area of a rectangle. """
if length <= 0 or width <= 0:
click.echo("Length and width must be positive values.")
else:
area = length * width
click.echo(f'The area of the rectangle with length {length} and width {width} is {area}')
@click.command()
@click.option('--length', prompt="Length of the rectangle", type=float)
@click.option('--width', prompt="Width of the rectangle", type=float)
def perimeter(length, width):
""" Calculate the perimeter of a rectangle. """
if length <= 0 or width <= 0:
click.echo("Length and width must be positive values.")
else:
perimeter = 2 * (length + width)
click.echo(f'The perimeter of the rectangle with length {length} and width {width} is {perimeter}')
# Register the commands with the group
rectangle.add_command(area)
rectangle.add_command(perimeter)
if __name__ == '__main__':
rectangle()
In this example,
@click.group()
Create a group of commands called a rectangle to organize related subcommands.@click.command()
defines individual subcommands such as area and perimeter.@click.option('--length')
and@click.option(‘--width’)
prompt the user for the length and width values, applying the type and input.rectangle.add_command(area)
andrectangle.add_command(perimeter)
Attach these subcommands to the group of rectangles.
When you run the CLI, you will use the circle command, followed by a subcommand (area or perimeter).
To calculate the area, run the following command:
python3 rectangle_calc.py area --length 2 --width 9
Production
The area of the rectangle with length 2.0 and width 9.0 is 18.0
To calculate the perimeter:
python3 rectangle_calc.py perimeter --length 2 --width 9
Production
The perimeter of the rectangle with length 2.0 and width 9.0 is 22.0
Document commands, options, and arguments
Documenting arguments, commands, and options is essential because it ensures that users can interact effectively with the application and quickly understand its capabilities.
The help parameter in the @click.option()
decorator describes the command line option. On the other hand, the commands and arguments are documented with the help of the docs string. Let's understand it with the help of an example:
import click
@click.command()
@click.option('--radius', type=float, default=5.0, help='Radius of the circle.')
@click.argument('color')
def describe_circle(radius, color):
"""
Describes a circle with a given radius and color.
Arguments:
color: The color of the circle.
"""
click.echo(f'The circle has a radius of {radius} and is colored {color}.')
if __name__ == '__main__':
describe_circle()
Now, open your terminal and invoke the help flag like:
The output will be:
Usage: circle.py (OPTIONS) COLOR
Describes a circle with a given radius and color.
Arguments:
color TEXT The color of the circle.
Options:
--radius FLOAT The radius of the circle. Defaults to 5.0.
--help Show this help message and exit.
This clarifies the command description, required arguments, and available options. Therefore, make sure to include complete documentation along with good functionality in your CLI application.
Concluding
In this guide, we explore the essential concepts needed to create command line applications with Click. I hope these explanations have clarified the basic concepts for you. For more advanced concepts and detailed usage, I recommend consulting the x/” rel=”noopener” target=”_blank”>Click documentation.
Kanwal Mehreen Kanwal is a machine learning engineer and technical writer with a deep passion for data science and the intersection of ai with medicine. She is the co-author of the eBook “Maximize Productivity with ChatGPT.” As a Google Generation Scholar 2022 for APAC, he champions diversity and academic excellence. She is also recognized as a Teradata Diversity in tech Scholar, Mitacs Globalink Research Scholar, and Harvard WeCode Scholar. Kanwal is a passionate advocate for change and founded FEMCodes to empower women in STEM fields.
Our Top 3 Partner Recommendations
1. Best VPN for Engineers: 3 Months Free – Stay safe online with a free trial
2. The best project management tool for technology teams – Drive team efficiency today
4. The best password management tool for tech teams – zero trust and zero knowledge security