Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Click: Having the group execute code AFTER a command

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?

like image 386
Ram Rachum Avatar asked Jul 02 '16 20:07

Ram Rachum


People also ask

How do you use the click function in Python?

Python click module is used to create command-line (CLI) applications. It is an easy-to-use alternative to the standard optparse and argparse modules. It allows arbitrary nesting of commands, automatic help page generation, and supports lazy loading of subcommands at runtime.

What is click Pass_context?

When a Click command callback is executed, it's passed all the non-hidden parameters as keyword arguments. Notably absent is the context. However, a callback can opt into being passed to the context object by marking itself with pass_context() .

What is Click option in Python?

Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It's the “Command Line Interface Creation Kit”. It's highly configurable but comes with sensible defaults out of the box.

Why use Click over Argparse?

Argparse is designed to parse arguments and provide extensive customization of cli help documentation. Click is designed to automatically handle common cli command tasks and quickly build a standard help menu.


1 Answers

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
like image 100
r-m-n Avatar answered Oct 12 '22 02:10

r-m-n