Python click.option() Examples

The following are 30 code examples of click.option(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module click , or try the search function .
Example #1
Source File: adapter.py    From django-click with MIT License 8 votes vote down vote up
def get_params(self, name):
        def show_help(ctx, param, value):
            if value and not ctx.resilient_parsing:
                click.echo(ctx.get_help(), color=ctx.color)
                ctx.exit()

        return [
            click.version_option(version=self.version, message="%(version)s"),
            click.option(
                "-h",
                "--help",
                is_flag=True,
                is_eager=True,
                expose_value=False,
                callback=show_help,
                help="Show this message and exit.",
            ),
        ] + self.common_options 
Example #2
Source File: cli.py    From yui with GNU Affero General Public License v3.0 7 votes vote down vote up
def load_config(func):
    """Decorator for add load config file option"""

    @functools.wraps(func)
    def internal(*args, **kwargs):
        filename = kwargs.pop('config')
        if filename is None:
            click.echo('--config option is required.', err=True)
            raise SystemExit(1)

        config = load(pathlib.Path(filename))
        kwargs['config'] = config
        return func(*args, **kwargs)

    decorator = click.option(
        '--config',
        '-c',
        type=click.Path(exists=True),
        envvar='YUI_CONFIG_FILE_PATH',
    )

    return decorator(internal) 
Example #3
Source File: __main__.py    From pylivetrader with Apache License 2.0 7 votes vote down vote up
def migrate_parameters(f):
    opts = [
        click.option(
            '-i', '--in-file',
            default=None,
            type=click.Path(
                exists=True, file_okay=True, dir_okay=False,
                readable=True, resolve_path=True),
            help='Path to the Quantopian/zipline algorithm file to migrate.'),
        click.option(
            '-o', '--out-file',
            default=None,
            type=click.Path(
                exists=False, file_okay=True, dir_okay=False,
                readable=True, resolve_path=True),
            help='Path to the pylivetrader output algorithm file.'),
        ]
    for opt in opts:
        f = opt(f)
    return f 
Example #4
Source File: test_clickDescendents.py    From isitfit with Apache License 2.0 7 votes vote down vote up
def test_ClickOption_failsWithPrompt(runner):
  @click.group()
  def isitfit(): pass

  @click.group()
  @click.option('--prompt', default='foo', prompt='my prompt', type=str)
  def cost(prompt): pass

  @click.command()
  def analyze(): pass

  cost.add_command(analyze)
  isitfit.add_command(cost)

  # invoke and assert
  result = runner.invoke(isitfit, ['cost', '--help'])
  assert False # the invoke above is expected to halt at the prompt and fail, but not working as expected ATM 
Example #5
Source File: __init__.py    From edgedb with Apache License 2.0 6 votes vote down vote up
def restore(ctx, file: str, allow_nonempty: bool) -> None:
    cargs = ctx.obj['connargs']
    conn = cargs.new_connection()
    dbname = conn.dbname

    try:
        if not is_empty_db(conn) and not allow_nonempty:
            raise click.ClickException(
                f'cannot restore into the {dbname!r} database: '
                f'the database is not empty; '
                f'consider using the --allow-nonempty option'
            )

        restorer = restoremod.RestoreImpl()
        restorer.restore(conn, file)
    finally:
        conn.close() 
Example #6
Source File: euler.py    From EulerPy with MIT License 6 votes vote down vote up
def euler_options(fn):
    """Decorator to link CLI options with their appropriate functions"""
    euler_functions = cheat, generate, preview, skip, verify, verify_all

    # Reverse functions to print help page options in alphabetical order
    for option in reversed(euler_functions):
        name, docstring = option.__name__, option.__doc__
        kwargs = {'flag_value': option, 'help': docstring}

        # Apply flag(s) depending on whether or not name is a single word
        flag = '--%s' % name.replace('_', '-')
        flags = [flag] if '_' in name else [flag, '-%s' % name[0]]

        fn = click.option('option', *flags, **kwargs)(fn)

    return fn 
Example #7
Source File: subcommand.py    From pygreynoise with MIT License 6 votes vote down vote up
def analyze(
    context, api_client, api_key, input_file, output_file, output_format, verbose
):
    """Analyze the IP addresses in a log file, stdin, etc."""
    if input_file is None:
        if sys.stdin.isatty():
            output = [
                context.command.get_usage(context),
                (
                    "Error: at least one text file must be passed "
                    "either through the -i/--input_file option or through a shell pipe."
                ),
            ]
            click.echo("\n\n".join(output))
            context.exit(-1)
        else:
            input_file = click.open_file("-")
    if output_file is None:
        output_file = click.open_file("-", mode="w")

    result = api_client.analyze(input_file)
    return result 
Example #8
Source File: subcommand.py    From pygreynoise with MIT License 6 votes vote down vote up
def filter(context, api_client, api_key, input_file, output_file, noise_only):
    """Filter the noise from a log file, stdin, etc."""
    if input_file is None:
        if sys.stdin.isatty():
            output = [
                context.command.get_usage(context),
                (
                    "Error: at least one text file must be passed "
                    "either through the -i/--input_file option or through a shell pipe."
                ),
            ]
            click.echo("\n\n".join(output))
            context.exit(-1)
        else:
            input_file = click.open_file("-")
    if output_file is None:
        output_file = click.open_file("-", mode="w")

    for chunk in api_client.filter(input_file, noise_only=noise_only):
        output_file.write(ANSI_MARKUP(chunk)) 
Example #9
Source File: click_options.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def show_trace_option(logging_mod=None, **kwargs):
    """A decorator that add --show_trace/-st option to decorated command"""

    if not isinstance(logging_mod, CustomLogging):
        raise TypeError("Logging object should be instance of CustomLogging.")

    names = ["--show_trace", "-st"]
    kwargs.setdefault("is_flag", True)
    kwargs.setdefault("default", False)
    kwargs.setdefault("expose_value", False)
    kwargs.setdefault("help", "Show the traceback for the exceptions")
    kwargs.setdefault("is_eager", True)

    def decorator(f):
        def _set_show_trace(ctx, param, value):
            if value:
                set_show_trace()

        return click.option(*names, callback=_set_show_trace, **kwargs)(f)

    return decorator 
Example #10
Source File: options.py    From yatsm with MIT License 6 votes vote down vote up
def opt_exampleimg(f):
    def callback(ctx, param, value):
        # Check if file qualifies alone
        if os.path.isfile(value):
            _value = value
        else:
            # Check if path relative to root qualifies
            _value = os.path.join(ctx.params['root'], value)
            if not os.path.isfile(_value):
                raise click.BadParameter('Cannot find example image '
                                         '"{f}"'.format(f=value))
            if not os.access(_value, os.R_OK):
                raise click.BadParameter('Found example image but cannot '
                                         'read from "{f}"'.format(f=_value))
        return os.path.abspath(_value)
    return click.option('--image', '-i',
                        default='example_img',
                        metavar='<image>',
                        show_default=True,
                        help='Example timeseries image',
                        callback=callback)(f) 
Example #11
Source File: test.py    From click-default-group with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_default_if_no_args():
    cli = DefaultGroup()

    @cli.command()
    @click.argument('foo', required=False)
    @click.option('--bar')
    def foobar(foo, bar):
        click.echo(foo)
        click.echo(bar)

    cli.set_default_command(foobar)
    assert r.invoke(cli, []).output.startswith('Usage:')
    assert r.invoke(cli, ['foo']).output == 'foo\n\n'
    assert r.invoke(cli, ['foo', '--bar', 'bar']).output == 'foo\nbar\n'
    cli.default_if_no_args = True
    assert r.invoke(cli, []).output == '\n\n' 
Example #12
Source File: cli.py    From zap-cli with MIT License 6 votes vote down vote up
def check_status(zap_helper, timeout):
    """
    Check if ZAP is running and able to receive API calls.

    You can provide a timeout option which is the amount of time in seconds
    the command should wait for ZAP to start if it is not currently running.
    This is useful to run before calling other commands if ZAP was started
    outside of zap-cli. For example:

        zap-cli status -t 60 && zap-cli open-url "http://127.0.0.1/"

    Exits with code 1 if ZAP is either not running or the command timed out
    waiting for ZAP to start.
    """
    with helpers.zap_error_handler():
        if zap_helper.is_running():
            console.info('ZAP is running')
        elif timeout is not None:
            zap_helper.wait_for_zap(timeout)
            console.info('ZAP is running')
        else:
            console.error('ZAP is not running')
            sys.exit(2) 
Example #13
Source File: options.py    From yatsm with MIT License 6 votes vote down vote up
def opt_resultdir(f):
    def callback(ctx, param, value):
        # Check if path qualifies alone
        if os.path.isdir(value):
            _value = value
        else:
            # Check if path relative to root qualifies
            _value = os.path.join(ctx.params['root'], value)
            if not os.path.isdir(_value):
                raise click.BadParameter('Cannot find result directory '
                                         '"{d}"'.format(d=value))
        if not os.access(_value, os.R_OK):
            raise click.BadParameter('Found result directory but cannot '
                                     'read from "{d}"'.format(d=_value))
        return os.path.abspath(_value)
    return click.option('--result', '-r',
                        default='YATSM',
                        metavar='<directory>',
                        show_default=True,
                        help='Directory of results',
                        callback=callback)(f)


# CALLBACKS 
Example #14
Source File: run.py    From web2board with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _validate_options(self, options):
        result = {}
        for k, v in options.items():
            _k = k.upper()
            # process obsolete options
            if _k in self.RENAMED_OPTIONS:
                click.secho(
                    "Warning! `%s` option is deprecated and will be "
                    "removed in the next release! Please use "
                    "`%s` instead." % (
                        k, self.RENAMED_OPTIONS[_k].lower()),
                    fg="yellow"
                )
                k = self.RENAMED_OPTIONS[_k].lower()
            result[k] = v
        return result 
Example #15
Source File: main.py    From learning2run with MIT License 6 votes vote down vote up
def master(exp_str, exp_file, master_socket_path, log_dir):
    # Start the master
    assert (exp_str is None) != (exp_file is None), 'Must provide exp_str xor exp_file to the master'
    if exp_str:
        exp = json.loads(exp_str)
    elif exp_file:
        with open(exp_file, 'r') as f:
            exp = json.loads(f.read())
    else:
        assert False
    log_dir = os.path.expanduser(log_dir) if log_dir else '/tmp/es_master_{}'.format(os.getpid())
    mkdir_p(log_dir)
    run_master({'unix_socket_path': master_socket_path}, log_dir, exp)


# @cli.command()
# @click.option('--master_host', required=True)
# @click.option('--master_port', default=6379, type=int)
# @click.option('--relay_socket_path', required=True)
# @click.option('--num_workers', type=int, default=0) 
Example #16
Source File: cli.py    From Watson with MIT License 6 votes vote down vote up
def stop(watson, at_):
    """
    Stop monitoring time for the current project.

    If `--at` option is given, the provided stopping time is used. The
    specified time must be after the beginning of the to-be-ended frame and must
    not be in the future.

    Example:

    \b
    $ watson stop --at 13:37
    Stopping project apollo11, started an hour ago and stopped 30 minutes ago. (id: e9ccd52) # noqa: E501
    """
    frame = watson.stop(stop_at=at_)
    output_str = u"Stopping project {}{}, started {} and stopped {}. (id: {})"
    click.echo(output_str.format(
        style('project', frame.project),
        (" " if frame.tags else "") + style('tags', frame.tags),
        style('time', frame.start.humanize()),
        style('time', frame.stop.humanize()),
        style('short_id', frame.id),
    ))
    watson.save() 
Example #17
Source File: shipyard.py    From batch-shipyard with MIT License 5 votes vote down vote up
def _show_config_option(f):
    def callback(ctx, param, value):
        clictx = ctx.ensure_object(CliContext)
        clictx.show_config = value
        return value
    return click.option(
        '--show-config',
        expose_value=False,
        is_flag=True,
        help='Show configuration',
        callback=callback)(f) 
Example #18
Source File: shipyard.py    From batch-shipyard with MIT License 5 votes vote down vote up
def monitor_option(f):
    def callback(ctx, param, value):
        clictx = ctx.ensure_object(CliContext)
        clictx.conf_monitor = value
        return value
    return click.option(
        '--monitor',
        expose_value=False,
        envvar='SHIPYARD_MONITOR_CONF',
        help='Resource monitoring config file',
        callback=callback)(f) 
Example #19
Source File: shipyard.py    From batch-shipyard with MIT License 5 votes vote down vote up
def _jobs_option(f):
    def callback(ctx, param, value):
        clictx = ctx.ensure_object(CliContext)
        clictx.conf_jobs = value
        return value
    return click.option(
        '--jobs',
        expose_value=False,
        envvar='SHIPYARD_JOBS_CONF',
        help='Jobs config file',
        callback=callback)(f) 
Example #20
Source File: mng.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def _process_configure_scalar(ctx, parameter, values):
    if values:
        raise click.UsageError(f'unexpected option: {next(iter(values))}')

    cfg_props = ctx.obj['conn'].fetchall('''
        WITH
            MODULE schema,
            Cfg := (SELECT ObjectType FILTER .name = <str>$typename)
        SELECT Cfg.pointers {
            name,
            cardinality,
            target: {
                name,
                __type__: {name},
                is_numeric := (
                    'std::anyreal' IN
                        Cfg.pointers.target[IS ScalarType].ancestors.name),
                is_bool := (
                    Cfg.pointers.target.name = 'std::bool'
                    OR 'std::bool' IN
                        Cfg.pointers.target[IS ScalarType].ancestors.name),
                is_str := (
                    Cfg.pointers.target.name = 'std::str'
                    OR any({'std::str', 'std::anyenum'} IN
                        Cfg.pointers.target[IS ScalarType].ancestors.name)),
            }
        } FILTER .name = <str>$propname;
    ''', typename=f'cfg::Config', propname=parameter)

    if len(cfg_props) == 0:
        raise click.UsageError(
            f'{parameter!r} is not a valid configuration parameter',
            ctx=ctx)

    return parameter, cfg_props[0].target, cfg_props[0].cardinality 
Example #21
Source File: shipyard.py    From batch-shipyard with MIT License 5 votes vote down vote up
def slurm_option(f):
    def callback(ctx, param, value):
        clictx = ctx.ensure_object(CliContext)
        clictx.conf_slurm = value
        return value
    return click.option(
        '--slurm',
        expose_value=False,
        envvar='SHIPYARD_SLURM_CONF',
        help='Slurm config file',
        callback=callback)(f) 
Example #22
Source File: commands.py    From sentinelhub-py with MIT License 5 votes vote down vote up
def _config_options(func):
    """ A helper function which joins click.option functions of each parameter from config.json
    """
    for param in SHConfig().get_params()[-1::-1]:
        func = click.option('--{}'.format(param), param,
                            help='Set new values to configuration parameter "{}"'.format(param))(func)
    return func 
Example #23
Source File: mng.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def options(options):
    def _decorator(func):
        for option in reversed(options):
            func = option(func)
        return func

    return _decorator 
Example #24
Source File: __main__.py    From pylivetrader with Apache License 2.0 5 votes vote down vote up
def shell_parameters(f):
    opts = [
        click.option(
            '-f', '--file',
            default=None,
            type=click.Path(
                exists=True, file_okay=True, dir_okay=False,
                readable=True, resolve_path=True),
            help='Path to the file taht contains algorithm to run.'),
        click.option(
            '-b', '--backend',
            default='alpaca',
            show_default=True,
            help='Broker backend to run algorithm with.'),
        click.option(
            '--backend-config',
            type=click.Path(
                exists=True, file_okay=True, dir_okay=False,
                readable=True, resolve_path=True),
            default=None,
            help='Path to broker backend config file.'),
        # click.argument('algofile', nargs=-1),
    ]
    for opt in opts:
        f = opt(f)
    return f 
Example #25
Source File: shipyard.py    From batch-shipyard with MIT License 5 votes vote down vote up
def _pool_option(f):
    def callback(ctx, param, value):
        clictx = ctx.ensure_object(CliContext)
        clictx.conf_pool = value
        return value
    return click.option(
        '--pool',
        expose_value=False,
        envvar='SHIPYARD_POOL_CONF',
        help='Pool config file',
        callback=callback)(f) 
Example #26
Source File: cli.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def run_command(info, host, port, reload, debugger, eager_loading,
                with_threads):
    """Runs a local development server for the Flask application.

    This local server is recommended for development purposes only but it
    can also be used for simple intranet deployments.  By default it will
    not support any sort of concurrency at all to simplify debugging.  This
    can be changed with the --with-threads option which will enable basic
    multithreading.

    The reloader and debugger are by default enabled if the debug flag of
    Flask is enabled and disabled otherwise.
    """
    from werkzeug.serving import run_simple

    debug = get_debug_flag()
    if reload is None:
        reload = bool(debug)
    if debugger is None:
        debugger = bool(debug)
    if eager_loading is None:
        eager_loading = not reload

    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)

    # Extra startup messages.  This depends a bit on Werkzeug internals to
    # not double execute when the reloader kicks in.
    if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        # If we have an import path we can print it out now which can help
        # people understand what's being served.  If we do not have an
        # import path because the app was loaded through a callback then
        # we won't print anything.
        if info.app_import_path is not None:
            print(' * Serving Flask app "%s"' % info.app_import_path)
        if debug is not None:
            print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))

    run_simple(host, port, app, use_reloader=reload,
               use_debugger=debugger, threaded=with_threads) 
Example #27
Source File: shipyard.py    From batch-shipyard with MIT License 5 votes vote down vote up
def _config_option(f):
    def callback(ctx, param, value):
        clictx = ctx.ensure_object(CliContext)
        clictx.conf_config = value
        return value
    return click.option(
        '--config',
        expose_value=False,
        envvar='SHIPYARD_CONFIG_CONF',
        help='Global config file',
        callback=callback)(f) 
Example #28
Source File: click_descendents.py    From isitfit with Apache License 2.0 5 votes vote down vote up
def isitfit_option_profile(name=None, **attrs):
  """
  Special option dedicated to --profile
  Was worth it because it was in cli.tags and cli.cost
  """
  from isitfit.utils import AwsProfileMan
  profile_man = AwsProfileMan()

  ret_opt = isitfit_option_base('--profile', type=str, default=profile_man.default(), callback=profile_man.validate_profile, prompt=profile_man.prompt(), help='Use a specific profile from your credential file.', envvar='AWS_PROFILE')
  return ret_opt 
Example #29
Source File: shipyard.py    From batch-shipyard with MIT License 5 votes vote down vote up
def _confirm_option(f):
    def callback(ctx, param, value):
        clictx = ctx.ensure_object(CliContext)
        clictx.yes = value
        return value
    return click.option(
        '-y', '--yes',
        expose_value=False,
        is_flag=True,
        help='Assume yes for all confirmation prompts',
        callback=callback)(f) 
Example #30
Source File: shipyard.py    From batch-shipyard with MIT License 5 votes vote down vote up
def federation_option(f):
    def callback(ctx, param, value):
        clictx = ctx.ensure_object(CliContext)
        clictx.conf_federation = value
        return value
    return click.option(
        '--federation',
        expose_value=False,
        envvar='SHIPYARD_FEDERATION_CONF',
        help='Federation config file',
        callback=callback)(f)