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.
# __init__.py
import pathlib
import click
import os
import typing
class ToolboxCLI(click.MultiCommand):
commands_folder = pathlib.Path.joinpath(
pathlib.Path(__file__).parent, "commands"
).resolve()
def list_commands(self, ctx: click.Context) -> typing.List[str]:
rv = []
for filename in os.listdir(self.commands_folder):
if filename.endswith(".py") and not filename.startswith("__init__"):
rv.append(filename[:-3])
rv.sort()
return rv
def get_command(
self, ctx: click.Context, cmd_name: str
) -> typing.Optional[click.Command]:
ns = {}
fn = pathlib.Path.joinpath(self.commands_folder, cmd_name + ".py")
with open(fn) as f:
code = compile(f.read(), fn, "exec")
eval(code, ns, ns)
return ns["cli"]
@click.group(cls=ToolboxCLI)
@click.option("--loglevel")
def cli(loglevel):
"Toolbox CLI "
# commands/admin.py
import click
@click.group() # <- how do i get global options for this command?
def cli():
pass
@cli.command()
def invite():
pass