Skip to content

Instantly share code, notes, and snippets.

@jzbruno
Last active April 5, 2021 19:04
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jzbruno/d167d256f6c426e2b6fdf2dbfc1ba3c9 to your computer and use it in GitHub Desktop.
Save jzbruno/d167d256f6c426e2b6fdf2dbfc1ba3c9 to your computer and use it in GitHub Desktop.
An example of conditionally prompting for options when a flag is set using the click library.
import click
def prompt_proxy(ctx, param, use_proxy):
if use_proxy:
host = ctx.params.get('proxy_host')
if not host:
host = click.prompt('Proxy host', default='localhost')
port = ctx.params.get('proxy_port')
if not port:
port = click.prompt('Proxy port', default=9000)
return (host, port)
@click.command()
@click.option('--use-proxy/--no-proxy', is_flag=True, default=False, callback=prompt_proxy)
@click.option('--proxy-host', is_eager=True)
@click.option('--proxy-port', is_eager=True, type=int)
def cli(use_proxy, proxy_host, proxy_port):
if use_proxy:
click.echo('Using proxy {}:{}'.format(*use_proxy))
else:
click.echo('Not using proxy.')
if __name__ == '__main__':
cli()
@jzbruno
Copy link
Author

jzbruno commented Jul 14, 2016

This is an example of conditionally prompting for options if an option flag is True. When handling options in this way we need to manually handle options entered on the command line.

Notes:

  • The flag cannot be set for is_eager. is_eager=False
  • The conditional options must be set for is_eager. is_eager=True
  • The conditional options must have their value exposed. expose_value=True

Examples:

  1. Default to False and don't prompt.

    > python click_conditional_options.py
    Not using proxy.
    
  2. Enable proxy and prompt.

    > python click_conditional_options.py --use-proxy
    Proxy host [localhost]:
    Proxy port [9000]:
    Using proxy localhost:9000
    
  3. Enable proxy and prompt for host only.

    > python click_conditional_options.py --use-proxy --proxy-port=9001
    Proxy host [localhost]:
    Using proxy localhost:9001
    

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment