【问题标题】:Python click application required parameters have precedence over sub command help optionPython点击应用所需参数优先于子命令帮助选项
【发布时间】:2019-04-23 20:12:06
【问题描述】:

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

例如,给定以下虚拟脚本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 选项的情况下获得显示添加命令的帮助?

【问题讨论】:

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


    【解决方案1】:

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

    自定义类:

    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
    

    【讨论】:

    • 对于在 click 中搜索所需参数的基本用法时发现此问题的读者:此解决方案仅是必要的,因为 OP 在组级别需要参数。当 required=True 仅在命令级别时,--help (no_args_is_help=True) 按预期工作。
    猜你喜欢
    • 2022-07-08
    • 2011-01-29
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 2011-11-18
    • 1970-01-01
    • 2019-03-14
    相关资源
    最近更新 更多