Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does click lib provide a way to print the builtin help message?

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 ?

like image 560
ruiruige1991 Avatar asked Mar 31 '17 12:03

ruiruige1991


People also ask

What is click library in Python?

Click, or “Command Line Interface Creation Kit” is a Python library for building command line interfaces. The three main points of Python Click are arbitrary nesting of commands, automatic help page generation, and supporting lazy loading of subcommands at runtime.

What is click Pass_context?

When a Click command callback is executed, it's passed all the non-hidden parameters as keyword arguments. Notably absent is the context. However, a callback can opt into being passed to the context object by marking itself with pass_context() .

How do you use the click function in Python?

Python click option namesClick derives the name of the option from the long name, if both are used. In the example, we create an option with both short and long names. The name of the variable passed to the function is string , derived from the longer option name. We run the program using both option names.

Which function is used to print a message on the terminal?

Printf command is used to print any message on the screen.


Video Answer


2 Answers

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)
like image 181
r-m-n Avatar answered Oct 02 '22 04:10

r-m-n


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")
like image 37
cmcginty Avatar answered Oct 02 '22 06:10

cmcginty