我正在用python实现一个classic 的CLI工具箱,并 Select click作为参数解析器.添加命令应该只是添加文件.从那里,命令将列在帮助中,依此类推.此零件正在通过click MultiCommand工作.
我还没有实现的是像loglevel
或configfile
这样的全球选项.我不希望每个命令都处理选项.我认为大多数全球选项都会创造出某种程度上的全球状态.如何做到这一点,我迷路了.
# __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