Python click应用程序必需的参数优先于子命令帮助选项

时间:2019-04-23 20:12:07

标签: python command-line-interface python-click

我正在使用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选项?

1 个答案:

答案 0 :(得分:1)

当请求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