Last active
January 1, 2026 18:16
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() |
Author
Thank you very much for this code snippet ๐
I improved it for my needs.
import click
def prompt_proxy(ctx, param, use_proxy):
if use_proxy:
host = ctx.params.get('proxy_host')
if not host:
ctx.params["host"] = click.prompt('Proxy host', default='localhost')
port = ctx.params.get('proxy_port')
if not port:
ctx.params["port"] = click.prompt('Proxy port', default=9000)
return use_proxy
@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(f"Using proxy {proxy_host}:{proxy_port}")
else:
click.echo('Not using proxy.')
if __name__ == '__main__':
cli()
Author
Glad to hear it was useful! ๐
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
Examples:
Default to False and don't prompt.
Enable proxy and prompt.
Enable proxy and prompt for host only.