16

I am using the click lib.

In my code , sometimes I want to print help msg , But the only way I know is :

python xxx --help

But I want to print the help msg in my code using a certain function , for example:

click.print_help_msg()

Is there a function like this ?

cmcginty
  • 113,384
  • 42
  • 163
  • 163
ruiruige1991
  • 615
  • 1
  • 10
  • 21

4 Answers4

22

You can use Command's get_help method

import click

@click.command()
@click.option('--name', help='The person to greet.')
def hello(name):
    """Simple program that greets NAME."""
    click.echo('Hello %s!' % name)

def print_help_msg(command):
    with click.Context(command) as ctx:
        click.echo(command.get_help(ctx))

>> print_help_msg(hello)
r-m-n
  • 14,192
  • 4
  • 69
  • 68
  • Sadly that's not working for my case I always get `AttributeError: 'name' object has no attribute 'allow_extra_args'` – lony Nov 16 '18 at 10:45
  • 1
    if you're using nested groups and end up with "Usage: [OPTIONS] COMMAND [ARGS]..." (ie. the root name is missing), then calling `with click.Context(command, info_name='mycli') as ctx:` will populate the name properly. – rcoup Oct 24 '19 at 12:25
  • And if you want to print the help of a `@click.group` you can use your annotated group method instead of `command`. – Andi Nov 18 '20 at 08:00
21

In click 5.x you can now use the get_current_context() method:

def print_help():
    ctx = click.get_current_context()
    click.echo(ctx.get_help())
    ctx.exit()

And if you're interested in just printing an error message and exiting, try:

def exit_with_msg():
    ctx = click.get_current_context()
    ctx.fail("Something unexpected happened")
cmcginty
  • 113,384
  • 42
  • 163
  • 163
  • Now with click 7.x, `ctx.exit()` gives an `AttributeError` as `exit()` has been removed. Exiting is implicit with Context unless it's utilized in a callback function (e.g. printing out your cli version via `MyCli.__version__`). – Casey Sep 03 '19 at 17:34
-1

You can use click.echo something like this :

click.echo('FooBar')

echo also supports color codes and filtering based on type such as :

click.echo('FooBar', err=True)

You can refer to the documentation for more understanding.

Satish Prakash Garg
  • 2,213
  • 2
  • 16
  • 25
-2

I modified the sample on click's documentation and came up with this, I haven't used it before though, or tested the below code.

@click.command()
@click.option('--help')
def help():
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo(get_help_message())

def get_help_message():
    return "I AM A HELP MESSAGE!"

Would something like this not work?

LismUK
  • 119
  • 1
  • 8