如果不正确或单击任务选项,则显示帮助

sca*_*one 3 python python-3.x python-click

当我将无效参数放入命令时,仅显示以下内容:

Usage: ugen.py [OPTIONS]

Error: Missing option "-o" / "--out_file".
Run Code Online (Sandbox Code Playgroud)

想像 --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
Run Code Online (Sandbox Code Playgroud)

Ste*_*uch 5

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

自定义命令类

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)
Run Code Online (Sandbox Code Playgroud)

使用自定义类

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

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

这是如何运作的?

这是有效的,因为 click 是一个设计良好的 OO 框架。该@click.command()装饰通常实例化一个click.Command对象,但允许这种行为将超过缠身与cls参数。因此,从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
Run Code Online (Sandbox Code Playgroud)

结果

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.
Run Code Online (Sandbox Code Playgroud)