Python - Click - Use fallback subcommand if no subcommand matches
21:59 05 Nov 2025

I have a tool that uses Click to define its CLI interface. It uses groups to achieve a subcommand hierarchy. So, if it is mytool, we have commands like mytool edit, mytool show, mytool execute script1.h etc.

The base command itself, mytool, has no positional arguments. It is defined a bit like this:

@click.group()
@click.option('--config-file', type=click.STRING, help='Config file to use')
def mytool(count, name):
    """Simple program that does things."""
    ....

@mytool.command()
@click.argument("script_name")
@click.pass_context
def execute(ctx, script_name):
    """Execute custom script"""
    ....

I want to add a new behavior. There are multilevel subcommands of various kinds. What I want is that, if no subcommands match the given command line input, for the tool to behave as if a specific default subcommand is called. If that subcommand is mytool execute, then I want a call like mytool script1.sh to behave as if mytool execute script1.sh was given, since this input normally matches no valid subcommands.

What is a good strategy to achieve this?

python command-line-interface python-click