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

标签 python python-3.x python-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

最佳答案

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

自定义命令类

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)

使用自定义类

要使用自定义类,只需将类传递给 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 参数覆盖此行为。因此,在我们自己的类中继承 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.

关于python - 如果不正确或点击任务选项显示帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50975203/

相关文章:

python - 如何根据 pyodbc 查询的结果创建 NumPy 数组?

python - 阻止在python中读取文件

python - 如何访问函数的内部变量并在 python 中更改其值?

python - Bokeh - 如何在两个不同的选项卡中拥有相同的小部件(或复制小部件)?

python - 根据条件删除嵌套列表中的列表

python - 通过使用 Foo() 参数运行子命令,在主单击组命令上实例化 Foo() 类

python click 应用程序失败并显示 "missing argument"但无法找到问题

python-click:格式化帮助文本

python - 根据条件使用外键计数注释 Django 查询集

python - 如何在Python中识别过拟合和欠拟合