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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Glad to hear it was useful! 😀