python Click Return the helper menu

…衆ロ難τιáo~ 提交于 2020-01-05 10:09:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!