Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Click Groups, Subcommands, and Prompts

Learn how to structure Python Click CLIs with groups, subcommands, and interactive prompts, including shared context, validation, and testing.

~3 min readPython
#Click#CLI#Python#Subcommands
Diagram showing a Click command group with subcommands and a prompt input field

When building a command-line tool with Click, groups let you organize related commands, subcommands define each action, and prompts collect input interactively. This article walks through how these pieces fit together, including how to share state between commands and validate prompt responses.

Building a Group with Subcommands

A Click group is a command that can contain other commands. Use @click.group() to create the root, then register each subcommand by decorating its function with @cli.command(). Here is a minimal example:

python
import click @click.group() def cli(): '''A simple CLI with subcommands.''' pass @cli.command() def init(): '''Initialize the project.''' click.echo('Initialized') @cli.command() def build(): '''Build the project.''' click.echo('Built') if __name__ == '__main__': cli()

When you run cli.py init, Click calls the init function. A group can also accept its own options; those values are passed to the group callback. If you store them on the context object, subcommands can read them later.

Sharing State with pass_context

Subcommands often need configuration from the group. Click provides @click.pass_context to inject a Context object into a command function. The context object is not literally the same object at every level, but its obj attribute is inherited by nested commands, so it is a convenient place to store shared state.

python
import click @click.group() @click.option('--verbose', is_flag=True) @click.pass_context def cli(ctx, verbose): '''A CLI with shared verbosity.''' ctx.ensure_object(dict) ctx.obj['verbose'] = verbose @cli.command() @click.pass_context def status(ctx): '''Show status.''' if ctx.obj.get('verbose'): click.echo('Verbose output enabled') click.echo('Status: OK')

Here, ctx.ensure_object(dict) initializes a dictionary to store shared data. Subcommands access it through ctx.obj. This pattern keeps the group and subcommands decoupled while allowing consistent configuration.

Adding Prompts to Subcommands

Prompts are useful when a subcommand needs input that is not suitable as a command-line argument, such as a secret or a choice that depends on runtime state. Use prompt=True in an option to ask interactively when the value is not provided.

python
@cli.command() @click.option('--name', prompt='Your name', help='Your name.') def greet(name): '''Greet the user.''' click.echo(f'Hello, {name}!')

If the user runs cli.py greet without --name, Click prompts for it. The prompt text can be customized, and hide_input=True turns it into a password prompt. For confirmation, use confirmation_prompt=True to ask twice.

python
@cli.command() @click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True) def login(password): '''Log in with a password.''' click.echo('Password accepted')

Validating Prompt Input

Click validates prompt input according to the option's type; for example, type=click.Choice(['dev', 'prod']) rejects values outside that set. For custom rules, use a callback. The callback receives the current context, the parameter, and the value, and returns the validated value.

python
def validate_email(ctx, param, value): if '@' not in value: raise click.BadParameter('Email must contain @') return value @cli.command() @click.option('--email', prompt=True, callback=validate_email) def subscribe(email): '''Subscribe with an email.''' click.echo(f'Subscribed {email}')

If the callback raises BadParameter, Click displays the error and asks for the value again. This keeps validation logic in one place and prevents the same checks from being duplicated across commands.

Nested Groups

Groups can be nested to create a hierarchy of subcommands. This is useful for tools with multiple domains, such as git remote add. Each nested group is itself a command that can have its own options and subcommands.

python
@click.group() def remote(): '''Manage remotes.''' pass @remote.command() @click.argument('name') @click.argument('url') def add(name, url): '''Add a remote.''' click.echo(f'Added remote {name}: {url}') cli.add_command(remote)

When nesting, pass_context still works at each level. The ctx.obj value is inherited, so data stored in a root callback is available to nested subcommands. However, avoid over-nesting; a flat structure is often easier to maintain.

Choosing Between Prompts and Arguments

Arguments are positional and, by default, required. Options with prompt=True can be omitted on the command line, but Click then asks for them interactively. If a value is always needed and should be supplied by scripts, use an argument. If it is sensitive or usually entered by a person, use a prompted option.

Use caseArgumentPrompted option
Scriptable and requiredYesNo
Interactive and optionalNoYes
Secret or sensitiveNoYes, with hide_input=True
Multiple valuesYesNo

A prompted option can also have a default. With prompt=True, default='world', Click shows a prompt with the default and pressing Enter accepts it.

Keeping the CLI Maintainable

As the number of subcommands grows, consistent naming and structure matter. Use clear group names and avoid deep nesting unless the domain requires it. Group common options in a decorator factory, and remember that a group callback runs when a subcommand is invoked by default. If you want it to run even when no subcommand is given, use @click.group(invoke_without_command=True).

python
def common_options(func): func = click.option('--verbose', is_flag=True)(func) func = click.option('--config', type=click.Path(exists=True))(func) return func @cli.command() @common_options def deploy(verbose, config): '''Deploy the app.''' click.echo(f'Deploying with config {config}')

This avoids repeating options across commands. For prompts, keep validation close to the prompt so errors are caught before the command body runs. When a prompt becomes complex, consider moving it to a separate function that returns the value, but keep the validation near the prompt.

Finally, test commands with Click's CliRunner to ensure prompts and subcommands behave as expected. The runner can simulate input and capture output, which is essential for verifying interactive behavior in a CI pipeline.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.