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

时间:2018-05-21 05:21:08

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

如何将默认选项设置为-h for Python click?

默认情况下,我的脚本在没有给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()

[OUT]:

$ 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.

4 个答案:

答案 0 :(得分:1)

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

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()

答案 1 :(得分:1)

如果您从click.Command继承并覆盖parse_args()方法,则可以创建一个默认的自定义类来帮助:

自定义类

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)

使用自定义类:

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

@click.command(cls=DefaultHelp)

这是如何工作的?

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

在这种情况下,我们覆盖click.Command.parse_args()并检查空参数列表。如果它是空的,那么我们调用帮助。此外,如果没有另外设置,此类将默认帮助['-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.

答案 2 :(得分:0)

我找到的最简单的方法

import click

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

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

答案 3 :(得分:0)

version 7.1开始,只需指定@click.command(no_args_is_help=True)