Skip to content
Advertisement

Click (Meta) Command to run a list of commands

I need to be able to trigger multiple click commands from one command on the CLI

Let’s say I have a click group

JavaScript

What functionality should I add to run an ordered list of the commands like the following?

JavaScript

The goal is that there are shared variables which get initialized for each of my commands. The init is expensive and I’d like to run the init exactly once.

Advertisement

Answer

To chain your commands, you have to pass chain=True to your group. For more information see this part of the documentation.

You could use the @click.pass_context decorator on the group to store the result of your initialisation:

JavaScript

and then you need to use the @click.pass_obj decorator on the commands to use the result object:

JavaScript

The pattern above is useful to share resources. I used it to share my sqlite db connection as an example.

For more information see the following documents:

pass_context documentation

pass_obj documentation

Another way to achieve this is to use multi command pipelines.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement