18

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?

2 Answers 2

28

You can use the @result_callback decorator

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


@cli.result_callback()
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
Sign up to request clarification or add additional context in comments.

2 Comments

Note that resultcallback has been renamed to result_callback
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.