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

4

12

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.
Almuce answered 21/5, 2018 at 5:21 Comment(1)
So if no options are given, then you want to default to help? You said: if no arguments is given, but your example only defines an option, it does not define any arguments.Tatar
T
6

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.
Tatar answered 23/5, 2018 at 14:57 Comment(0)
D
18

As of version 7.1, one can simply specify @click.command(no_args_is_help=True).

Despot answered 24/8, 2020 at 18:2 Comment(0)
S
11

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()
Selfheal answered 21/5, 2018 at 5:30 Comment(2)
Hmmm but that imposes a duh command and when I do python test_click.py duh, it still doesn't print out the help message =(Almuce
Could I also check if *args == None?Almuce
T
6

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.
Tatar answered 23/5, 2018 at 14:57 Comment(0)
F
1

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()
Fields answered 22/11, 2019 at 16:11 Comment(1)
Perfect! Just what I wanted. Everything else was very convoluted.Hehre

© 2022 - 2024 — McMap. All rights reserved.