python Click Return the helper menu

2019-07-24 08:02发布

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

2条回答
你好瞎i
2楼-- · 2019-07-24 08:23

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.

查看更多
Emotional °昔
3楼-- · 2019-07-24 08:46

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.

查看更多
登录 后发表回答