如何将 Python 点击的默认选项设置为 -h?

How to set the default option as -h for Python click?

如何将 Python 点击的默认选项设置为 -h?

默认情况下,如果没有向 duh.py:

提供任何参数,我的脚本将不显示任何内容
import click


CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])

@click.command(context_settings=CONTEXT_SETTINGS)
@click.option('--toduhornot', is_flag=True, help='prints "duh..."')
def duh(toduhornot):
    if toduhornot:
        click.echo('duh...')

if __name__ == '__main__':
    duh()

[输出]:

$ python3 test_click.py -h
Usage: test_click.py [OPTIONS]

Options:
  --toduhornot  prints "duh..."
  -h, --help    Show this message and exit.



$ python3 test_click.py --toduhornot
duh...


$ python3 test_click.py 

问题:

如上图,默认不打印信息python3 test_click.py.

有没有办法在没有给出参数的情况下将默认选项设置为 -h,例如

$ python3 test_click.py 
Usage: test_click.py [OPTIONS]

Options:
  --toduhornot  prints "duh..."
  -h, --help    Show this message and exit.

您的结构不是推荐的结构,您应该使用:

import click


CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])


@click.group(context_settings=CONTEXT_SETTINGS)
def cli():
    pass


@cli.command(help='prints "duh..."')
def duh():
    click.echo('duh...')

if __name__ == '__main__':
    cli()

然后python test_click.py将打印帮助信息:

Usage: test_click.py [OPTIONS] COMMAND [ARGS]...

Options:
  -h, --help  Show this message and exit.

Commands:
  duh  prints "duh..."

所以你可以用python test_click.py duh调用duh

更新

import click


CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])

@click.command(context_settings=CONTEXT_SETTINGS)
@click.option('--toduhornot', is_flag=True, help='prints "duh..."')
def duh(toduhornot):
    if toduhornot:
        click.echo('duh...')
    else:
        with click.Context(duh) as ctx:
            click.echo(ctx.get_help())

if __name__ == '__main__':
    duh()

如果您继承自 click.Command 并重写 parse_args() 方法,您可以创建一个自定义 class 来默认帮助,例如:

自定义Class

import click

class DefaultHelp(click.Command):
    def __init__(self, *args, **kwargs):
        context_settings = kwargs.setdefault('context_settings', {})
        if 'help_option_names' not in context_settings:
            context_settings['help_option_names'] = ['-h', '--help']
        self.help_flag = context_settings['help_option_names'][0]
        super(DefaultHelp, self).__init__(*args, **kwargs)

    def parse_args(self, ctx, args):
        if not args:
            args = [self.help_flag]
        return super(DefaultHelp, self).parse_args(ctx, args)

使用自定义 Class:

要使用自定义 class,请将 cls 参数传递给 @click.command() 装饰器,例如:

@click.command(cls=DefaultHelp)

这是如何工作的?

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

在这种情况下,我们覆盖 click.Command.parse_args() 并检查空参数列表。如果它是空的,那么我们调用帮助。此外,如果未另行设置,class 会将帮助默认为 ['-h', '--help']

测试代码:

@click.command(cls=DefaultHelp)
@click.option('--toduhornot', is_flag=True, help='prints "duh..."')
def duh(toduhornot):
    if toduhornot:
        click.echo('duh...')

if __name__ == "__main__":
    commands = (
        '--toduhornot',
        '',
        '--help',
        '-h',
    )

    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)
            duh(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)]
-----------
> --toduhornot
duh...
-----------
> 
Usage: test.py [OPTIONS]

Options:
  --toduhornot  prints "duh..."
  -h, --help    Show this message and exit.
-----------
> --help
Usage: test.py [OPTIONS]

Options:
  --toduhornot  prints "duh..."
  -h, --help    Show this message and exit.
-----------
> -h
Usage: test.py [OPTIONS]

Options:
  --toduhornot  prints "duh..."
  -h, --help    Show this message and exit.

我找到的最简单的方法

import click

@click.command()
@click.option('--option')
@click.pass_context

def run(ctx, option):
    if not option:
        click.echo(ctx.get_help())
        ctx.exit()

version 7.1 开始,可以简单地指定 @click.command(no_args_is_help=True)