Search code examples
pythonclickcommand-line-interfacepython-click

add a command to all leaf level commands in a python click chain commands


I have a chain of commands somethig like this.

@click.group()
@click.option('--debug/--no-debug', default=False)
def cli(debug):
    click.echo('Debug mode is %s' % ('on' if debug else 'off'))

@cli.command()  
def sync1():
    click.echo('Syncing 1')
@cli.command()  
def sync2():
    click.echo('Syncing 1')
tool.py
Usage: tool.py [OPTIONS] COMMAND [ARGS]...

Options:
  --debug / --no-debug
  --help                Show this message and exit.

Commands:
  sync1
  sync2

This is how I would run my command in a nested fashion.

tool.py sync1 --help

tool.py sync2 --help

now imagine every leaf level command (i.e sync1 and sync2 in this case) calls some API and I want to print the name of that API.

What is the best way to achieve without changing all leaf level function (i.e sync1/sync2).


Solution

  • One way you could achieve this is with a result callback decorator.

    @cli.resultcallback()
    def process_result(result, **kwargs):
        click.echo('Print your API name here')
    

    That should allow code to be executed after the command was invoked. However, I'm not sure if the order of execution matters to you.

    Hope it helps!