1

Consider the following minimal Click script mytool.py:

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)

if __name__ == '__main__':
    hello()

How can I access the Context object Click generates for this script when I call it with

python mytool.py

In particular access to the the info_name attribute is important (so that, when I programmatically want to display the help message, the script name mytool.py is populated.(*)


(*) I know that I can generate a new Context object via click.Context(hello) but this context does not contain by itself the info_name property. Of course I can figure out the script name manually, but Click certainly creates a default context with the script name and I believe that one would be the best to access. (See also Does click lib provide a way to print the builtin help message?)

1 Answer 1

3

https://click.palletsprojects.com/en/7.x/complex/

Add @click.pass_context as the final decorator and it becomes the first parameter in your function.

Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I was after. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.