Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect when '--help' has been called?

My Click 7.0 application has one group, having multiple commands, called by the main cli function like so:

import click

@click.group()
@click.pass_context
def cli(ctx):
   "This is cli helptext"

    click.echo('cli called')
    click.echo('cli args: {0}'.format(ctx.args))

@cli.group(chain=True)
@click.option('-r', '--repeat', default=1, type=click.INT, help='repeat helptext')
@click.pass_context
def chainedgroup(ctx, repeat):
    "This is chainedgroup helptext"

    for _ in range(repeat):
        click.echo('chainedgroup called')
    click.echo('chainedgroup args: {0}'.format(ctx.args))

@chainedgroup.command()
@click.pass_context
def command1(ctx):
    "This is command1 helptext"

    print('command1 called')
    print('command1 args: {0}'.format(ctx.args))

@chainedgroup.command()
@click.pass_context
def command2(ctx):
    "This is command2 helptext"

    print('command2 called')
    print('command2 args: {0}'.format(ctx.args))

Run:

$ testcli --help
$ testcli chainedgroup --help
$ testcli chainedgroup command1 --help

The help-text displays as expected--except that the parent functions are inadvertently run in the process. A single conditional checking to see if '--help' is contained in ctx.args should be enough to solve this problem, but does anyone know how/when '--help' is passed? Because with this code, ctx.args is empty every time.

like image 344
Noob Saibot Avatar asked Oct 28 '25 05:10

Noob Saibot


1 Answers

If argparse is not an option, how about:

if '--help' in sys.argv:
...
like image 59
foxpal Avatar answered Oct 29 '25 20:10

foxpal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!