How to set the default option as -h for Python cli

2020-03-30 07:02发布

问题:

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

By default, my script, shows nothing when no arguments is given to the 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 

Question:

As shown above, the default prints no information python3 test_click.py.

Is there a way such that, the default option is set to -h if no arguments is given, e.g.

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

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

回答1:

If you inherit from click.Command and override the parse_args() method, you can create a custom class to default to help like:

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

Using Custom Class:

To use the custom class, pass the cls parameter to @click.command() decorator like:

@click.command(cls=DefaultHelp)

How does this work?

This works because click is a well designed OO framework. The @click.command() decorator usually instantiates a click.Command object but allows this behavior to be over ridden with the cls parameter. So it is a relatively easy matter to inherit from click.Command in our own class and over ride the desired methods.

In this case we over-ride click.Command.parse_args() and check for an empty argument list. If it is empty then we invoke the help. In addition this class will default the help to ['-h', '--help'] if it is not otherwise set.

Test Code:

@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

Results:

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:

Your structure is not the recommended one, you should use:

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

And then python test_click.py will print help message:

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

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

Commands:
  duh  prints "duh..."

So you can use python test_click.py duh to call duh.

Update

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


回答3:

Easiest approach I've found

import click

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

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