Skip to content
Advertisement

How to define common python-click options for multiple commands?

In python 3.8 I want to define some click options that are common to multiple commands. I tried the following piece of code:

JavaScript

But when I try to run the command

JavaScript

I get an error

JavaScript

What I want, is that the command list has the following three options: verbose, path and list-option and that the command find has the following three options: verbose, path and find-option. I do not want to define the options for verbose and path twice.

Is there a way to do this?

I also tried to use @click.pass_context but that does not seem to solev the issue.

Advertisement

Answer

The way you currently defined it it will work, but the --verbose option belongs to the main command group, so you’d need to call it as python script.py --verbose list (and my_find_command and my_list_command won’t receive it as an argument, only cli).

To use the same option across multiple commands without repeating yourself too much, you can just assign it to a variable and then use it twice:

JavaScript

Unrelated, but while we’re at it: There’s a simpler way of grouping commands, without having to do cli.add_command(my_find_command): Just use @cli.command() instead of @click.command():

JavaScript

If there’s several options you want to apply, you can define your own decorator that calls all those options on the argument:

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