gpt4 book ai didi

python - 使用 click : add unspecified options for command as dictionary 具有多个命令的命令行界面

转载 作者:行者123 更新时间:2023-12-01 08:28:24 25 4
gpt4 key购买 nike

我有一个通过单击构建的命令行界面,它实现了多个命令。

现在我想将未指定的命名选项传递到一个命令中,该命令此处名为 command1 例如选项的数量及其名称应该能够灵活变化。

import click


@click.group(chain=True)
@click.pass_context
def cli(ctx, **kwargs):
return True


@cli.command()
@click.option('--command1-option1', type=str)
@click.option('--command1-option2', type=str)
@click.pass_context
def command1(ctx, **kwargs):
"""Add command1."""
ctx.obj['command1_args'] = {}
for k, v in kwargs.items():
ctx.obj['command1_args'][k] = v
return True


@cli.command()
@click.argument('command2-argument1', type=str)
@click.pass_context
def command2(ctx, **kwargs):
"""Add command2."""
print(ctx.obj)
print(kwargs)
return True


if __name__ == '__main__':
cli(obj={})

我已经调查过forwarding unknown options就像 this question但问题是我必须在第一个命令之后调用(chanin)其他命令,这些命令必须被断言,例如此调用必须有效,但可以使用 command1 的任意选项:

$python cli.py command1 --command1-option1 foo --command1-option2 bar command2 'hello'

那么如何将未指定的命名选项添加到单个命令并同时(在其之后)调用(链接)另一个命令?

最佳答案

找到自定义类 here ,可以根据您的情况进行调整。

使用自定义类:

要使用自定义类,只需使用 click.command() 装饰器的 cls 参数,如下所示:

@cli.command(cls=AcceptAllCommand)
@click.pass_context
def command1(ctx, **kwargs):
"""Add command1."""
...

测试代码:

import click

class AcceptAllCommand(click.Command):

def make_parser(self, ctx):
"""Hook 'make_parser' and allow the opt dict to find any option"""
parser = super(AcceptAllCommand, self).make_parser(ctx)
command = self

class AcceptAllDict(dict):

def __contains__(self, item):
"""If the parser does no know this option, add it"""

if not super(AcceptAllDict, self).__contains__(item):
# create an option name
name = item.lstrip('-')

# add the option to our command
click.option(item)(command)

# get the option instance from the command
option = command.params[-1]

# add the option instance to the parser
parser.add_option(
[item], name.replace('-', '_'), obj=option)
return True

# set the parser options to our dict
parser._short_opt = AcceptAllDict(parser._short_opt)
parser._long_opt = AcceptAllDict(parser._long_opt)

return parser


@click.group(chain=True)
@click.pass_context
def cli(ctx, **kwargs):
""""""


@cli.command(cls=AcceptAllCommand)
@click.pass_context
def command1(ctx, **kwargs):
"""Add command1."""
ctx.obj['command1_args'] = {}
for k, v in kwargs.items():
ctx.obj['command1_args'][k] = v


@cli.command()
@click.argument('command2-argument1', type=str)
@click.pass_context
def command2(ctx, **kwargs):
"""Add command2."""
print(ctx.obj)
print(kwargs)


if __name__ == "__main__":
commands = (
"command1 --cmd1-opt1 foo --cmd1-opt2 bar command2 hello",
'--help',
)

import sys, time

time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for cmd in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + cmd)
time.sleep(0.1)
cli(cmd.split(), obj={})

except BaseException as exc:
if str(exc) != '0' and \
not isinstance(exc, (click.ClickException, SystemExit)):
raise

结果:

Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> command1 --cmd1-opt1 foo --cmd1-opt2 bar command2 hello
{'command1_args': {'cmd1_opt1': 'foo', 'cmd1_opt2': 'bar'}}
{'command2_argument1': 'hello'}
-----------
> --help
Usage: test.py [OPTIONS] COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...

Options:
--help Show this message and exit.

Commands:
command1 Add command1.
command2 Add command2.

关于python - 使用 click : add unspecified options for command as dictionary 具有多个命令的命令行界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54073767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com