Skip to content
Advertisement

Global options for python-click MultiCommand

I’m implementing a classical CLI toolbox with python and I selected click as my argument parser. Adding a command should just be adding a file. From there the command is listed in the help and so on. This part is working through a click MultiCommand.

What I didn’t achieve yet are global options like loglevel or configfile. I don’t want every command to deal with the options. I think most global options create somewhat global state. How do achieve this, I’m lost. I also think that this something that could very well be covered by the official documentation.

JavaScript

Advertisement

Answer

click_example.py:

JavaScript

Above: Add allow_interspersed_args so --log-level can be accessed anywhere

Note: I renamed --loglevel -> --log-level

In commands/admin_cli.py:

JavaScript

Use @click.pass_context and Context.parent to fetch the params of the root scope.

Setup: chmod +x ./click_example.py

Output:

JavaScript

P.S. I am using something similar to this pattern in a project of mine (vcspull), see vcspull/cli/. Inside of it I pass the log level param to a setup_logger(log=None, level='INFO') function. This source is MIT licensed so you / anyone is free to use it as an example.

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