I want to use a value in my configuration (which I load into my context) as the default value for a click command option. I've read this section of the documentation, and I don't think I'm understanding what I need do.
This is my example script:
import sys
import click
@click.group()
@click.pass_context
def cli(ctx):
"""
CLI
"""
ctx.ensure_object(dict)
ctx.obj['DEFAULT_ENVIRONMENT'] = "dev"
@cli.command()
@click.option('-e', '--environment', required=True, default=click.get_current_context().obj['DEFAULT_ENVIRONMENT'])
def show_env(environment):
click.echo(environment)
if __name__ == '__main__':
cli()
The goal, if I run python cli.py show-env
, is to get it to output dev
(because I didn't pass the parameter as it's loaded from context).
This fails with
Traceback (most recent call last):
File "testcli.py", line 15, in <module>
@click.option('-e', '--environment', required=True, default=click.get_current_context().obj['DEFAULT_ENVIRONMENT'])
File "/home/devuser/.virtualenvs/cli/lib/python3.6/site-packages/click/globals.py", line 26, in get_current_context
raise RuntimeError('There is no active click context.')
RuntimeError: There is no active click context.
I have also tried by using @pass_context
on my show_env
command like so:
@cli.command()
@click.option('-e', '--environment', required=True, default=ctx.obj['DEFAULT_ENVIRONMENT'])
@click.pass_context
def show_env(ctx, environment):
click.echo(environment)
Which fails because ctx
isn't defined at that point.
Traceback (most recent call last):
File "testcli.py", line 15, in <module>
@click.option('-e', '--environment', required=True, default=ctx.obj['DEFAULT_ENVIRONMENT'])
NameError: name 'ctx' is not defined
Am I able to use my context to set a command option default value?