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?
Python Click: Having the group execute code AFTER a command
Asked Answered
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
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!!
© 2022 - 2024 — McMap. All rights reserved.
resultcallback
has been renamed toresult_callback
– Sol