问题
I just started using python click module and I would like to have it automatically bring up the '--help' function anytime click throws an error.
test.py
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', default=Adam,
help='The person to great.')
def test(name):
print name
If I was to run the script from the command line as test.py --no_such_thing. Is there a way I could get the --help to come up instead of the normal :Error no Option --no_such_thing
回答1:
In short, you need to modify the method click.exceptions.UsageError.show
.
But, I have posted a more in-depth answer to this question, along with sample code, in the answer to this SO post.
回答2:
If you're using Click 4.0+, you can disable automatic error handling for unknown options using Context.ignore_unknown_options and Context.allow_extra_args:
import click
@click.command(context_settings={
'allow_extra_args': True,
'ignore_unknown_options': True,
})
@click.pass_context
def hello(ctx):
if ctx.args:
print(hello.get_help(ctx))
if __name__ == "__main__":
hello()
In that case, your command will receive the remaining arguments in ctx.args
list. The disadvantage is that you need to handle errors yourself or the program will fail silently.
More information can be found at the docs in the Forwarding Unknown Options section.
来源:https://stackoverflow.com/questions/35642202/python-click-return-the-helper-menu