如果不正确或点击任务选项显示帮助

display help if incorrect or mission option in click

当我向命令输入无效参数时,只显示:

Usage: ugen.py [OPTIONS]

Error: Missing option "-o" / "--out_file".

我想像 --help 选项一样显示整个帮助信息

我的修饰函数:

@click.command(name="ugen")
@click.help_option("-h", "--help")
@click.option(
    "-o", "--out_file",
    help="Output file where data is written.",
    required=True
)
@click.option(
    "-i", "--in_file", multiple=True,
    help=(
        "Input file/s from which data is read. "
        "Can be provided multiple times. "
        "Although always with specifier -i/--in_file."
    ),
    required=True
)
def main(out_file, in_file):
    code here

您可以挂接命令调用,然后根据需要显示帮助,如:

自定义命令Class

import click

class ShowUsageOnMissingError(click.Command):
    def __call__(self, *args, **kwargs):
        try:
            return super(ShowUsageOnMissingError, self).__call__(
                *args, standalone_mode=False, **kwargs)
        except click.MissingParameter as exc:
            exc.ctx = None
            exc.show(file=sys.stdout)
            click.echo()
            try:
                super(ShowUsageOnMissingError, self).__call__(['--help'])
            except SystemExit:
                sys.exit(exc.exit_code)

使用自定义 Class

要使用自定义 class,只需将 class 传递给 click.command() 装饰器,例如:

@click.command(cls=ShowUsageOnMissingError)
@click.option("-o", help="Output file where data is written.", required=True)
def cli(o):
    ...

这是如何工作的?

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

在这种情况下,我们覆盖 __call__() 并在打印异常后打印帮助。

测试代码

@click.command(cls=ShowUsageOnMissingError)
@click.option("-o", help="Output file where data is written.", required=True)
def cli(o):
    click.echo(o)


if __name__ == "__main__":
    commands = (
        '-o outfile',
        '',
        '--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.2 (default, Jul 17 2017, 23:14:31)
[GCC 5.4.0 20160609]
-----------
> -o outfile
outfile
-----------
>
Error: Missing option "-o".

Usage: test.py [OPTIONS]

Options:
  -o TEXT  Output file where data is written.  [required]
  --help   Show this message and exit.
-----------
> --help
Usage: test.py [OPTIONS]

Options:
  -o TEXT  Output file where data is written.  [required]
  --help   Show this message and exit.