Python Click: Having the group execute code AFTER a command
Asked Answered
Y

2

17

I have a click.group() defined, with about 10 commands in it. I understand how to use a group to run code before the code in the command, but I also want to run some code AFTER each command is run. Is that possible with click?

Ymir answered 2/7, 2016 at 20:43 Comment(0)
J
26

You can use the @resultcallback decorator

@click.group()
def cli():
    click.echo('Before command')


@cli.resultcallback()
def process_result(result, **kwargs):
    click.echo('After command')


@cli.command()
def command():
    click.echo('Command')


if __name__ == '__main__':
    cli()

Output:

$ python cli.py command
Before command
Command
After command
Jovitta answered 3/7, 2016 at 8:29 Comment(1)
Note that resultcallback has been renamed to result_callbackSol
I
2

This worked for me on Click==7.0. Have not tried resultcallback

$ cat check.py 
import click

@click.group()
@click.pass_context
def cli(ctx):
    print("> Welcome!!")
    ctx.call_on_close(_on_close)

def _on_close():
    print("> Done!!")

@cli.command()
def hello():
    print("Hello")

if __name__ == '__main__':
    cli()

Output:

$ python3 check.py hello
> Welcome!!
Hello
> Done!!

Documentation

Intercellular answered 30/5, 2021 at 3:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.