Language: Python
CLI/Utils
Click was created by Armin Ronacher to simplify the creation of complex command-line interfaces while maintaining code readability and flexibility. It is widely used in Python projects for building robust CLI tools and applications.
Click is a Python package for creating command-line interfaces (CLI) with composable commands, automatic help page generation, and support for environment variables and configuration files.
pip install clickconda install -c conda-forge clickClick allows you to define commands and options as Python functions with decorators. It handles parsing, validation, and help text generation automatically, making CLI development faster and more consistent.
import click
@click.command()
def hello():
click.echo('Hello, World!')
if __name__ == '__main__':
hello()Defines a simple command-line program that prints 'Hello, World!' when run.
import click
@click.command()
@click.option('--name', prompt='Your name', help='The person to greet.')
def greet(name):
click.echo(f'Hello, {name}!')
if __name__ == '__main__':
greet()Adds an option `--name` to the CLI, prompting the user for input if not provided, and then prints a greeting.
import click
@click.group()
def cli():
pass
@click.command()
def init():
click.echo('Initialized')
@click.command()
def drop():
click.echo('Dropped')
cli.add_command(init)
cli.add_command(drop)
if __name__ == '__main__':
cli()Defines a CLI group with multiple commands, allowing structured CLI tools with subcommands.
import click
@click.command()
@click.argument('filename')
def read_file(filename):
with open(filename) as f:
click.echo(f.read())
if __name__ == '__main__':
read_file()Uses a positional argument `filename` to read and print the content of a file.
import click
@click.group()
@click.pass_context
def cli(ctx):
ctx.ensure_object(dict)
@cli.command()
@click.pass_context
def step1(ctx):
click.echo('Step 1')
ctx.obj['step'] = 1
@cli.command()
@click.pass_context
def step2(ctx):
click.echo(f'Step 2, previous step = {ctx.obj.get("step")}')
if __name__ == '__main__':
cli(obj={})Demonstrates sharing context between chained commands in a CLI group.
Use decorators `@click.command`, `@click.option`, and `@click.argument` to define commands clearly.
Organize multiple commands using `@click.group()` for better structure.
Use `click.echo()` instead of `print()` for consistent output handling.
Leverage `click.Context` for passing objects or state between commands.
Use the built-in help system and `prompt` feature to improve CLI usability.