问题
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 ?
回答1:
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)
回答2:
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")
回答3:
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?
回答4:
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.
来源:https://stackoverflow.com/questions/43140639/does-click-lib-provide-a-way-to-print-the-builtin-help-message