Skip to content

Instantly share code, notes, and snippets.

@jzbruno
Last active January 1, 2026 18:16
Show Gist options
  • Select an option

  • Save jzbruno/d167d256f6c426e2b6fdf2dbfc1ba3c9 to your computer and use it in GitHub Desktop.

Select an option

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()
@chrisdecker1201
Copy link

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()

@jzbruno
Copy link
Author

jzbruno commented Jan 1, 2026

Glad to hear it was useful! ๐Ÿ˜€

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