Python click.option() Examples

The following are 30 code examples for showing how to use click.option(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module click , or try the search function .

Example 1
Project: django-click   Author: GaretJax   File: adapter.py    License: MIT License 7 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
Project: yui   Author: item4   File: cli.py    License: 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
Project: EulerPy   Author: iKevinY   File: euler.py    License: 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 4
Project: pygreynoise   Author: GreyNoise-Intelligence   File: subcommand.py    License: 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 5
Project: pygreynoise   Author: GreyNoise-Intelligence   File: subcommand.py    License: 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 6
Project: calm-dsl   Author: nutanix   File: click_options.py    License: 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 7
Project: yatsm   Author: ceholden   File: options.py    License: 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 8
Project: yatsm   Author: ceholden   File: options.py    License: 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 9
Project: schemathesis   Author: kiwicom   File: __init__.py    License: MIT License 6 votes vote down vote up
def replay(
    cassette_path: str,
    id_: Optional[str],
    status: Optional[str] = None,
    uri: Optional[str] = None,
    method: Optional[str] = None,
) -> None:
    """Replay a cassette.

    Cassettes in VCR-compatible format can be replayed.
    For example, ones that are recorded with ``store-network-log`` option of `schemathesis run` command.
    """
    click.secho(f"{bold('Replaying cassette')}: {cassette_path}")
    with open(cassette_path) as fd:
        cassette = yaml.load(fd, Loader=SafeLoader)
    click.secho(f"{bold('Total interactions')}: {len(cassette['http_interactions'])}\n")
    for replayed in cassettes.replay(cassette, id_=id_, status=status, uri=uri, method=method):
        click.secho(f"  {bold('ID')}              : {replayed.interaction['id']}")
        click.secho(f"  {bold('URI')}             : {replayed.interaction['request']['uri']}")
        click.secho(f"  {bold('Old status code')} : {replayed.interaction['response']['status']['code']}")
        click.secho(f"  {bold('New status code')} : {replayed.response.status_code}\n") 
Example 10
Project: Watson   Author: TailorDev   File: cli.py    License: 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 11
Project: click-default-group   Author: click-contrib   File: test.py    License: 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
Project: web2board   Author: bq   File: run.py    License: 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 13
Project: learning2run   Author: AdamStelmaszczyk   File: main.py    License: 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 14
Project: edgedb   Author: edgedb   File: __init__.py    License: 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 15
Project: zap-cli   Author: Grunny   File: cli.py    License: 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 16
Project: pylivetrader   Author: alpacahq   File: __main__.py    License: Apache License 2.0 6 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 17
Project: isitfit   Author: autofitcloud   File: test_clickDescendents.py    License: Apache License 2.0 6 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 18
Project: Paradrop   Author: ParadropLabs   File: device.py    License: Apache License 2.0 5 votes vote down vote up
def change(ctx, option, value):
    """
    Change one setting in the host configuration.
    """
    url = ctx.obj['base_url'] + "/config/hostconfig"
    req = router_request("GET", url, dump=False)
    config = req.json()

    change_json(config, option, value)
    data = {
        'config': config
    }
    router_request("PUT", url, json=data) 
Example 19
Project: catt   Author: skorokithakis   File: cli.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_default_map():
    """
    Returns a dictionary of the form:
        {"option": "value",
         "aliases": {"device1": "device_name"}}
    """

    config = readconfig()
    conf_dict = {section: dict(config.items(section)) for section in config.sections()}
    default_map = conf_dict["options"]
    default_map["aliases"] = conf_dict["aliases"]
    return default_map 
Example 20
Project: uptick   Author: bitshares   File: decorators.py    License: MIT License 5 votes vote down vote up
def customchain(**kwargsChain):
    """ This decorator allows you to access ``ctx.bitshares`` which is
        an instance of BitShares. But in contrast to @chain, this is a
        decorator that expects parameters that are directed right to
        ``BitShares()``.

        ... code-block::python

                @main.command()
                @click.option("--worker", default=None)
                @click.pass_context
                @customchain(foo="bar")
                @unlock
                def list(ctx, worker):
                   print(ctx.obj)

    """

    def wrap(f):
        @click.pass_context
        @verbose
        def new_func(ctx, *args, **kwargs):
            newoptions = ctx.obj
            newoptions.update(kwargsChain)
            ctx.bitshares = BitShares(**newoptions)
            ctx.blockchain = ctx.bitshares
            set_shared_bitshares_instance(ctx.bitshares)
            return ctx.invoke(f, *args, **kwargs)

        return update_wrapper(new_func, f)

    return wrap 
Example 21
Project: ampy   Author: scientifichackers   File: cli.py    License: MIT License 5 votes vote down vote up
def run(local_file, no_output):
    """Run a script and print its output.

    Run will send the specified file to the board and execute it immediately.
    Any output from the board will be printed to the console (note that this is
    not a 'shell' and you can't send input to the program).

    Note that if your code has a main or infinite loop you should add the --no-output
    option.  This will run the script and immediately exit without waiting for
    the script to finish and print output.

    For example to run a test.py script and print any output until it finishes:

      ampy --port /board/serial/port run test.py

    Or to run test.py and not wait for it to finish:

      ampy --port /board/serial/port run --no-output test.py
    """
    # Run the provided file and print its output.
    board_files = files.Files(_board)
    try:
        output = board_files.run(local_file, not no_output, not no_output)
        if output is not None:
            print(output.decode("utf-8"), end="")
    except IOError:
        click.echo(
            "Failed to find or read input file: {0}".format(local_file), err=True
        ) 
Example 22
Project: maubot   Author: maubot   File: cliq.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def option(short: str, long: str, message: str = None, help: str = None,
           click_type: Union[str, Callable[[str], Any]] = None, inq_type: str = None,
           validator: Validator = None, required: bool = False, default: str = None,
           is_flag: bool = False, prompt: bool = True) -> Callable[[Callable], Callable]:
    if not message:
        message = long[2].upper() + long[3:]
    click_type = validator.click_type if isinstance(validator, ClickValidator) else click_type
    if is_flag:
        click_type = yesno

    def decorator(func) -> Callable:
        click.option(short, long, help=help, type=click_type)(func)
        if not prompt:
            return func
        if not hasattr(func, "__inquirer_questions__"):
            func.__inquirer_questions__ = {}
        q = {
            "type": (inq_type if isinstance(inq_type, str)
                     else ("input" if not is_flag
                           else "confirm")),
            "name": long[2:],
            "message": message,
        }
        if default is not None:
            q["default"] = default
        if required:
            q["validator"] = Required(validator)
        elif validator:
            q["validator"] = validator
        func.__inquirer_questions__[long[2:]] = q
        return func

    return decorator 
Example 23
Project: EulerPy   Author: iKevinY   File: euler.py    License: MIT License 5 votes vote down vote up
def main(option, problem):
    """Python-based Project Euler command line tool."""
    # No problem given (or given option ignores the problem argument)
    if problem == 0 or option in {skip, verify_all}:
        # Determine the highest problem number in the current directory
        files = problem_glob()
        problem = max(file.num for file in files) if files else 0

        # No Project Euler files in current directory (no glob results)
        if problem == 0:
            # Generate the first problem file if option is appropriate
            if option not in {cheat, preview, verify_all}:
                msg = "No Project Euler files found in the current directory."
                click.echo(msg)
                option = generate

            # Set problem number to 1
            problem = 1

        # --preview and no problem; preview the next problem
        elif option is preview:
            problem += 1

        # No option and no problem; generate next file if answer is
        # correct (verify() will exit if the solution is incorrect)
        if option is None:
            verify(problem)
            problem += 1
            option = generate

    # Problem given but no option; decide between generate and verify
    elif option is None:
        option = verify if Problem(problem).glob else generate

    # Execute function based on option
    option(problem)
    sys.exit(0) 
Example 24
Project: pygreynoise   Author: GreyNoise-Intelligence   File: decorator.py    License: MIT License 5 votes vote down vote up
def pass_api_client(function):
    """Create API client form API key and pass it to subcommand.

    :param function: Subcommand that returns a result from the API.
    :type function: callable
    :returns: Wrapped function that prints subcommand results
    :rtype: callable

    """

    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        context = click.get_current_context()
        api_key = context.params.get("api_key")
        config = load_config()

        if api_key is None:
            if not config["api_key"]:
                prog_name = context.parent.info_name
                click.echo(
                    "\nError: API key not found.\n\n"
                    "To fix this problem, please use any of the following methods "
                    "(in order of precedence):\n"
                    "- Pass it using the -k/--api-key option.\n"
                    "- Set it in the GREYNOISE_API_KEY environment variable.\n"
                    "- Run {!r} to save it to the configuration file.\n".format(
                        "{} setup".format(prog_name)
                    )
                )
                context.exit(-1)
            api_key = config["api_key"]

        api_client = GreyNoise(
            api_key=api_key, timeout=config["timeout"], integration_name="cli"
        )
        return function(api_client, *args, **kwargs)

    return wrapper 
Example 25
Project: pygreynoise   Author: GreyNoise-Intelligence   File: decorator.py    License: MIT License 5 votes vote down vote up
def gnql_command(function):
    """Decorator that groups decorators common to gnql query and stats subcommands."""

    @click.command()
    @click.argument("query", required=False)
    @click.option("-k", "--api-key", help="Key to include in API requests")
    @click.option("-i", "--input", "input_file", type=click.File(), help="Input file")
    @click.option(
        "-o", "--output", "output_file", type=click.File(mode="w"), help="Output file"
    )
    @click.option(
        "-f",
        "--format",
        "output_format",
        type=click.Choice(["json", "txt", "xml"]),
        default="txt",
        help="Output format",
    )
    @click.option("-v", "--verbose", count=True, help="Verbose output")
    @pass_api_client
    @click.pass_context
    @echo_result
    @handle_exceptions
    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        return function(*args, **kwargs)

    return wrapper 
Example 26
Project: pygreynoise   Author: GreyNoise-Intelligence   File: decorator.py    License: MIT License 5 votes vote down vote up
def ip_lookup_command(function):
    """Decorator that groups decorators common to ip and quick subcommand."""

    @click.command()
    @click.argument("ip_address", callback=ip_addresses_parameter, nargs=-1)
    @click.option("-k", "--api-key", help="Key to include in API requests")
    @click.option("-i", "--input", "input_file", type=click.File(), help="Input file")
    @click.option(
        "-o", "--output", "output_file", type=click.File(mode="w"), help="Output file"
    )
    @click.option(
        "-f",
        "--format",
        "output_format",
        type=click.Choice(["json", "txt", "xml"]),
        default="txt",
        help="Output format",
    )
    @pass_api_client
    @click.pass_context
    @echo_result
    @handle_exceptions
    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        return function(*args, **kwargs)

    return wrapper 
Example 27
Project: datasette   Author: simonw   File: cli.py    License: Apache License 2.0 5 votes vote down vote up
def convert(self, config, param, ctx):
        if ":" not in config:
            self.fail('"{}" should be name:value'.format(config), param, ctx)
            return
        name, value = config.split(":", 1)
        if name not in DEFAULT_CONFIG:
            self.fail(
                "{} is not a valid option (--help-config to see all)".format(name),
                param,
                ctx,
            )
            return
        # Type checking
        default = DEFAULT_CONFIG[name]
        if isinstance(default, bool):
            try:
                return name, value_as_boolean(value)
            except ValueAsBooleanError:
                self.fail(
                    '"{}" should be on/off/true/false/1/0'.format(name), param, ctx
                )
                return
        elif isinstance(default, int):
            if not value.isdigit():
                self.fail('"{}" should be an integer'.format(name), param, ctx)
                return
            return name, int(value)
        elif isinstance(default, str):
            return name, value
        else:
            # Should never happen:
            self.fail("Invalid option") 
Example 28
Project: recruit   Author: Frank-qlu   File: cli.py    License: Apache License 2.0 5 votes vote down vote up
def _validate_key(ctx, param, value):
    """The ``--key`` option must be specified when ``--cert`` is a file.
    Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.
    """
    cert = ctx.params.get('cert')
    is_adhoc = cert == 'adhoc'

    if sys.version_info < (2, 7):
        is_context = cert and not isinstance(cert, (text_type, bytes))
    else:
        is_context = isinstance(cert, ssl.SSLContext)

    if value is not None:
        if is_adhoc:
            raise click.BadParameter(
                'When "--cert" is "adhoc", "--key" is not used.',
                ctx, param)

        if is_context:
            raise click.BadParameter(
                'When "--cert" is an SSLContext object, "--key is not used.',
                ctx, param)

        if not cert:
            raise click.BadParameter(
                '"--cert" must also be specified.',
                ctx, param)

        ctx.params['cert'] = cert, value

    else:
        if cert and not (is_adhoc or is_context):
            raise click.BadParameter(
                'Required when using "--cert".',
                ctx, param)

    return value 
Example 29
Project: qb   Author: Pinafore   File: checkpoint.py    License: MIT License 5 votes vote down vote up
def fetch(variable, environment_variable):
    if variable is None:
        env_variable = os.environ.get(environment_variable)
        if env_variable is not None and env_variable != "":
            return env_variable
        else:
            raise ValueError('You must set {} or pass the variable as an option'.format(
                environment_variable))
    else:
        return variable 
Example 30
Project: click-default-group   Author: click-contrib   File: test.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_default_command_with_arguments():
    assert r.invoke(cli, ['--foo', 'foooo']).output == 'foooo\n'
    assert 'no such option' in r.invoke(cli, ['-x']).output