gpt4 book ai didi

Python 单击应用程序所需的参数优先于子命令帮助选项

转载 作者:行者123 更新时间:2023-12-01 07:58:44 25 4
gpt4 key购买 nike

我正在构建一个 click 7.x申请 Python 3.6在获取子命令的帮助时遇到一些问题。我有一个必需的全局选项,当我对任何子命令运行帮助时,该选项被报告为缺失。

例如,给定以下虚拟脚本 cli.py:

import click


@click.group()
@click.option('--directory', required=True)
def cli(directory):
"""
this is a tool that has an add and remove command
"""
click.echo(directory)


@cli.command()
@click.overwrite('--overwrite', is_flag=True)
def add(overwrite):
"""
this is the add command
"""
click.echo("add overwrite={}".format(overwrite))


@cli.command()
def remove():
"""
this is the remove command
"""
click.echo('remove')


if __name__ == '__main__':
cli()

当我运行以下命令时:

python cli.py --help

我得到了所需的输出:

Usage cli.py [OPTIONS] COMMAND [ARGS]...

this is a tool that has an add and remove command

Options:
--directory TEXT [required]
--help Show this message and exit.

Commands:
add this is the add command
remove this is the remove command

但是如果我运行这个:

python cli.py add --help

我收到以下错误:

Usage cli.py [OPTIONS] COMMAND [ARGS]...
Try "cli.py --help" for help.

Error: Missing option "--directory"

如何在无需提供 --directory 选项的情况下获取要显示的 add 命令的帮助?

最佳答案

您可以使用自定义的 click.Group 类在请求 --help 时忽略所需的参数,如下所示:

自定义类:

class IgnoreRequiredWithHelp(click.Group):
def parse_args(self, ctx, args):
try:
return super(IgnoreRequiredWithHelp, self).parse_args(ctx, args)
except click.MissingParameter as exc:
if '--help' not in args:
raise

# remove the required params so that help can display
for param in self.params:
param.required = False
return super(IgnoreRequiredWithHelp, self).parse_args(ctx, args)

使用自定义类:

要使用自定义类,请将其作为 cls 参数传递给组装饰器,如下所示:

@click.group(cls=IgnoreRequiredWithHelp)
....
def my_group():
....

这是如何工作的?

这是有效的,因为 click 是一个设计良好的 OO 框架。 @click.group() 装饰器通常会实例化 click.Group 对象,但允许使用 cls 参数覆盖此行为。因此,在我们自己的类中继承 click.Group 并覆盖所需的方法是一件相对容易的事情。

在本例中,我们重写 click.Group.parse_args() 并捕获 click.MissingParameter 异常。然后,我们从所有参数中否定 required 属性,并重试解析。

测试代码:

import click

@click.group(cls=IgnoreRequiredWithHelp)
@click.option('--directory', required=True)
def cli(directory):
"""
this is a tool that has an add and remove command
"""
click.echo(directory)

@cli.command()
@click.option('--overwrite', is_flag=True)
def add(overwrite):
"""
this is the add command
"""
click.echo("add overwrite={}".format(overwrite))


@cli.command()
def remove():
"""
this is the remove command
"""
click.echo('remove')


if __name__ == "__main__":
commands = (
'add --help',
'--help',
'--directory a_dir add'
'',
)

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())

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)]
-----------
> add --help

Usage: test.py add [OPTIONS]

this is the add command

Options:
--overwrite
--help Show this message and exit.
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...

this is a tool that has an add and remove command

Options:
--directory TEXT
--help Show this message and exit.

Commands:
add this is the add command
remove this is the remove command
-----------
> --directory a_dir add
a_dir
add overwrite=False

关于Python 单击应用程序所需的参数优先于子命令帮助选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55818737/

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