Python click.get_current_context() Examples

The following are 30 code examples of click.get_current_context(). 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: terminal.py    From pros-cli2 with Mozilla Public License 2.0 7 votes vote down vote up
def terminal(port):
    click.echo(click.style('NOTE: This is an early prototype of the terminal.'
                           ' Nothing is guaranteed to work.', bold=True))
    if port == 'default':
        if len(prosflasher.ports.list_com_ports()) == 1:
            port = prosflasher.ports.list_com_ports()[0].device
        elif len(prosflasher.ports.list_com_ports()) > 1:
            click.echo('Multiple ports were found:')
            click.echo(prosflasher.ports.create_port_list())
            port = click.prompt('Select a port to open',
                                type=click.Choice([p.device for p in prosflasher.ports.list_com_ports()]))
        else:
            click.echo('No ports were found.')
            click.get_current_context().abort()
            sys.exit()
    ser = prosflasher.ports.create_serial(port, serial.PARITY_NONE)
    term = proscli.serial_terminal.Terminal(ser)
    signal.signal(signal.SIGINT, term.stop)
    term.start()
    while term.alive:
        time.sleep(0.005)
    term.join()
    ser.close()
    print('Exited successfully')
    sys.exit(0) 
Example #2
Source File: cli.py    From crane with MIT License 6 votes vote down vote up
def main(**parsed_settings):
    click_context = click.get_current_context()
    click_context.color = True  # GitLab doesn't report terminal type correctly so we need to force it

    settings.update(parsed_settings)
    rancher.session.auth = settings['access_key'], settings['secret_key']

    try:
        deployment.load_from_settings(settings)
    except UpgradeFailed:
        sys.exit(1)  # we handled it gracefully already

    hooks.dispatch('before_upgrade')

    try:
        upgrade(deployment.services)
    except Exception as ex:
        hooks.dispatch('after_upgrade_failure')
        if isinstance(ex, UpgradeFailed):
            sys.exit(1)  # we handled it gracefully already
        raise
    else:
        hooks.dispatch('after_upgrade_success') 
Example #3
Source File: adapter.py    From django-click with MIT License 6 votes vote down vote up
def execute(self, *args, **kwargs):
        """
        Called when run through `call_command`. `args` are passed through,
        while `kwargs` is the __dict__ of the return value of
        `self.create_parser('', name)` updated with the kwargs passed to
        `call_command`.
        """
        # Remove internal Django command handling machinery
        kwargs.pop("skip_checks", None)
        parent_ctx = click.get_current_context(silent=True)
        with self.make_context("", list(args), parent=parent_ctx) as ctx:
            # Rename kwargs to to the appropriate destination argument name
            opt_mapping = dict(self.map_names())
            arg_options = {
                opt_mapping.get(key, key): value for key, value in six.iteritems(kwargs)
            }

            # Update the context with the passed (renamed) kwargs
            ctx.params.update(arg_options)

            # Invoke the command
            self.invoke(ctx) 
Example #4
Source File: main.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def calmrepl():
    """Enable an interactive prompt shell

    > :help

    REPL help:

    External Commands:

      prefix external commands with "!"

    Internal Commands:

      prefix internal commands with ":"

      :exit, :q, :quit  exits the repl

      :?, :h, :help     displays general help information
"""
    repl(click.get_current_context()) 
Example #5
Source File: helper.py    From twtxt with MIT License 6 votes vote down vote up
def style_tweet(tweet, porcelain=False):
    conf = click.get_current_context().obj["conf"]
    limit = conf.character_limit

    if porcelain:
        return "{nick}\t{url}\t{tweet}".format(
            nick=tweet.source.nick,
            url=tweet.source.url,
            tweet=str(tweet))
    else:
        if sys.stdout.isatty() and not tweet.text.isprintable():
            return None
        styled_text = format_mentions(tweet.text)
        len_styling = len(styled_text) - len(click.unstyle(styled_text))
        final_text = textwrap.shorten(styled_text, limit + len_styling) if limit else styled_text
        timestamp = tweet.absolute_datetime if conf.use_abs_time else tweet.relative_datetime
        return "➤ {nick} ({time}):\n{tweet}".format(
            nick=click.style(tweet.source.nick, bold=True),
            tweet=final_text,
            time=click.style(timestamp, dim=True)) 
Example #6
Source File: helper.py    From twtxt with MIT License 6 votes vote down vote up
def validate_text(ctx, param, value):
    conf = click.get_current_context().obj["conf"]
    if isinstance(value, tuple):
        value = " ".join(value)

    if not value and not sys.stdin.isatty():
        value = click.get_text_stream("stdin").read()

    if value:
        value = value.strip()
        if conf.character_warning and len(value) > conf.character_warning:
            click.confirm("✂ Warning: Tweet is longer than {0} characters. Are you sure?".format(
                conf.character_warning), abort=True)
        return value
    else:
        raise click.BadArgumentUsage("Text can’t be empty.") 
Example #7
Source File: callbacks.py    From notifiers with MIT License 6 votes vote down vote up
def _notify(p, **data):
    """The callback func that will be hooked to the ``notify`` command"""
    message = data.get("message")
    if not message and not sys.stdin.isatty():
        message = click.get_text_stream("stdin").read()
    data["message"] = message

    data = clean_data(data)

    ctx = click.get_current_context()
    if ctx.obj.get("env_prefix"):
        data["env_prefix"] = ctx.obj["env_prefix"]

    rsp = p.notify(**data)
    rsp.raise_on_errors()
    click.secho(f"Succesfully sent a notification to {p.name}!", fg="green") 
Example #8
Source File: conductor.py    From pros-cli2 with Mozilla Public License 2.0 6 votes vote down vote up
def register(cfg, location, kernel):
    first_run(cfg)
    kernel_version = kernel
    if kernel_version == 'latest':
        templates = local.get_local_templates(pros_cfg=cfg.pros_cfg,
                                              template_types=[TemplateTypes.kernel])  # type: List[Identifier]
        if not templates or len(templates) == 0:
            click.echo('No templates have been downloaded! Use `pros conduct download` to download the latest kernel or'
                       ' specify a kernel manually.')
            click.get_current_context().abort()
            sys.exit()
        kernel_version = sorted(templates, key=lambda t: semver.Version(t.version))[-1].version
        proscli.utils.debug('Resolved version {} to {}'.format(kernel, kernel_version))

    cfg = prosconfig.ProjectConfig(location, create=True, raise_on_error=True)
    cfg.kernel = kernel_version
    if not location:
        click.echo('Location not specified, registering current directory.')
    click.echo('Registering {} with kernel {}'.format(location or os.path.abspath('.'), kernel_version))
    cfg.save()


# endregion 
Example #9
Source File: tools.py    From q2cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def citations(path):
    import qiime2.sdk
    import io
    from q2cli.core.config import CONFIG
    ctx = click.get_current_context()

    try:
        result = qiime2.sdk.Result.load(path)
    except Exception as e:
        header = 'There was a problem loading %s as a QIIME 2 result:' % path
        q2cli.util.exit_with_error(e, header=header)

    if result.citations:
        with io.StringIO() as fh:
            result.citations.save(fh)
            click.echo(fh.getvalue(), nl=False)
        ctx.exit(0)
    else:
        click.echo(CONFIG.cfg_style('problem', 'No citations found.'),
                   err=True)
        ctx.exit(1) 
Example #10
Source File: output_formatter.py    From globus-cli with Apache License 2.0 6 votes vote down vote up
def print_unix_response(res):
    res = _jmespath_preprocess(res)
    try:
        unix_formatted_print(res)
    # Attr errors indicate that we got data which cannot be unix formatted
    # likely a scalar + non-scalar in an array, though there may be other cases
    # print good error and exit(2) (Count this as UsageError!)
    except AttributeError:
        click.echo(
            "UNIX formatting of output failed."
            "\n  "
            "This usually means that data has a structure which cannot be "
            "handled by the UNIX formatter."
            "\n  "
            "To avoid this error in the future, ensure that you query the "
            'exact properties you want from output data with "--jmespath"',
            err=True,
        )
        click.get_current_context().exit(2) 
Example #11
Source File: transfer.py    From globus-cli with Apache License 2.0 6 votes vote down vote up
def autoactivate(client, endpoint_id, if_expires_in=None):
    """
    Attempts to auto-activate the given endpoint with the given client
    If auto-activation fails, parses the returned activation requirements
    to determine which methods of activation are supported, then tells
    the user to use 'globus endpoint activate' with the correct options(s)
    """
    kwargs = {}
    if if_expires_in is not None:
        kwargs["if_expires_in"] = if_expires_in

    res = client.endpoint_autoactivate(endpoint_id, **kwargs)
    if res["code"] == "AutoActivationFailed":

        message = (
            "The endpoint could not be auto-activated and must be "
            "activated before it can be used.\n\n"
            + activation_requirements_help_text(res, endpoint_id)
        )

        click.echo(message, err=True)
        click.get_current_context().exit(1)

    else:
        return res 
Example #12
Source File: get_option_vals.py    From globus-cli with Apache License 2.0 5 votes vote down vote up
def outformat_is_json():
    """
    Only safe to call within a click context.
    """
    ctx = click.get_current_context()
    state = ctx.ensure_object(CommandState)
    return state.outformat_is_json() 
Example #13
Source File: audit.py    From anchore with Apache License 2.0 5 votes vote down vote up
def init_nav_contexts():
    try:
        # use the obj from the current click context. This is a bit hacky, but works as long as this method is
        # invoked in an execution context of click
        anchore_config = click.get_current_context().obj
        nav = navigator.Navigator(anchore_config=anchore_config, imagelist=imagelist, allimages=contexts['anchore_allimages'])
        return nav
    except Exception as err:
        anchore_print_err("explore operation failed")
        success = False
        ecode = 1

    if not success:
        contexts['anchore_allimages'].clear()
        sys.exit(ecode) 
Example #14
Source File: query.py    From anchore with Apache License 2.0 5 votes vote down vote up
def init_nav_contexts():
    try:
        # use the obj from the current click context. This is a bit hacky, but works as long as this method is
        # invoked in an execution context of click
        anchore_config = click.get_current_context().obj
        nav = navigator.Navigator(anchore_config=anchore_config, imagelist=imagelist, allimages=contexts['anchore_allimages'])
        return nav
    except Exception as err:
        anchore_print_err("explore operation failed")
        success = False
        ecode = 1

    if not success:
        contexts['anchore_allimages'].clear()
        sys.exit(ecode) 
Example #15
Source File: get_option_vals.py    From globus-cli with Apache License 2.0 5 votes vote down vote up
def verbosity():
    """
    Only safe to call within a click context.
    """
    ctx = click.get_current_context()
    state = ctx.ensure_object(CommandState)
    return state.verbosity 
Example #16
Source File: local_id.py    From globus-cli with Apache License 2.0 5 votes vote down vote up
def local_id(personal):
    """Display UUID of locally installed endpoint"""
    if personal:
        try:
            ep_id = LocalGlobusConnectPersonal().endpoint_id
        except IOError as e:
            click.echo(e, err=True)
            click.get_current_context().exit(1)

        if ep_id is not None:
            click.echo(ep_id)
        else:
            click.echo("No Globus Connect Personal installation found.")
            click.get_current_context().exit(1) 
Example #17
Source File: cli.py    From deon with MIT License 5 votes vote down vote up
def main(checklist, output_format, output, overwrite, multicell):
    """Easily create an ethics checklist for your data science project.

    The checklist will be printed to standard output by default. Use the --output option to write
    to a file instead.
    """
    try:
        result = create(checklist, output_format, output, overwrite, multicell)
    except ExtensionException:
        with click.get_current_context() as ctx:
            msg = "Output requires a file name with a supported extension.\n\n"
            raise click.ClickException(msg + ctx.get_help())
    except FormatException:
        with click.get_current_context() as ctx:
            msg = f"File format {output_format} is not supported.\n\n"
            raise click.ClickException(msg + ctx.get_help())
    except MulticellException:
        with click.get_current_context() as ctx:
            msg = f"Multicell is for use with jupyter format only. You used: {output_format}.\n\n"
            raise click.ClickException(msg + ctx.get_help())
    else:
        # write output or print to stdout
        if result:
            click.echo(result)
        else:
            click.echo(f"Checklist successfully written to file {output}.") 
Example #18
Source File: get_option_vals.py    From globus-cli with Apache License 2.0 5 votes vote down vote up
def outformat_is_text():
    """
    Only safe to call within a click context.
    """
    ctx = click.get_current_context()
    state = ctx.ensure_object(CommandState)
    return state.outformat_is_text() 
Example #19
Source File: get_option_vals.py    From globus-cli with Apache License 2.0 5 votes vote down vote up
def get_jmespath_expression():
    """
    Only safe to call within a click context.
    """
    ctx = click.get_current_context()
    state = ctx.ensure_object(CommandState)
    return state.jmespath_expr 
Example #20
Source File: shell_completion.py    From globus-cli with Apache License 2.0 5 votes vote down vote up
def print_completer_option(f):
    def callback(ctx, param, value):
        if not value or ctx.resilient_parsing:
            return
        if value == "BASH":
            click.echo(BASH_SHELL_COMPLETER)
        elif value == "ZSH":
            click.echo(ZSH_SHELL_COMPLETER)
        else:
            raise ValueError("Unsupported shell completion")
        click.get_current_context().exit(0)

    f = click.option(
        "--completer",
        "--bash-completer",
        hidden=True,
        is_eager=True,
        expose_value=False,
        flag_value="BASH",
        callback=callback,
    )(f)
    f = click.option(
        "--zsh-completer",
        hidden=True,
        is_eager=True,
        expose_value=False,
        flag_value="ZSH",
        callback=callback,
    )(f)
    return f 
Example #21
Source File: pystack.py    From pystack with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cli_main(pid, include_greenlet, debugger, verbose):
    '''Print stack of python process.

    $ pystack <pid>
    '''
    try:
        print_stack(pid, include_greenlet, debugger, verbose)
    except DebuggerNotFound as e:
        click.echo('DebuggerNotFound: %s' % e.args[0], err=True)
        click.get_current_context().exit(1) 
Example #22
Source File: dnsgate.py    From dnsgate with MIT License 5 votes vote down vote up
def blacklist(domains):
    for domain in domains:
        append_to_local_rule_file(CUSTOM_BLACKLIST, domain)
    context = click.get_current_context()
    context.invoke(generate) 
Example #23
Source File: dnsgate.py    From dnsgate with MIT License 5 votes vote down vote up
def whitelist(domains):
    for domain in domains:
        append_to_local_rule_file(CUSTOM_WHITELIST, domain)
    context = click.get_current_context()
    context.invoke(generate) 
Example #24
Source File: ctl.py    From patroni with MIT License 5 votes vote down vote up
def request_patroni(member, method='GET', endpoint=None, data=None):
    ctx = click.get_current_context()  # the current click context
    request_executor = ctx.obj.get('__request_patroni')
    if not request_executor:
        request_executor = ctx.obj['__request_patroni'] = PatroniRequest(ctx.obj)
    return request_executor(member, method, endpoint, data) 
Example #25
Source File: main.py    From typer with MIT License 5 votes vote down vote up
def get_callback(
    *,
    callback: Optional[Callable] = None,
    params: Sequence[click.Parameter] = [],
    convertors: Dict[str, Callable[[str], Any]] = {},
    context_param_name: str = None,
) -> Optional[Callable]:
    if not callback:
        return None
    parameters = get_params_from_function(callback)
    use_params: Dict[str, Any] = {}
    for param_name in parameters:
        use_params[param_name] = None
    for param in params:
        use_params[param.name] = param.default

    def wrapper(**kwargs: Any) -> Any:
        for k, v in kwargs.items():
            if k in convertors:
                use_params[k] = convertors[k](v)
            else:
                use_params[k] = v
        if context_param_name:
            use_params[context_param_name] = click.get_current_context()
        return callback(**use_params)  # type: ignore

    update_wrapper(wrapper, callback)
    return wrapper 
Example #26
Source File: base.py    From hokusai with MIT License 5 votes vote down vote up
def console():
    """Start an interactive console session"""
    repl(click.get_current_context()) 
Example #27
Source File: tools.py    From q2cli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def export_data(input_path, output_path, output_format):
    import qiime2.util
    import qiime2.sdk
    import distutils
    from q2cli.core.config import CONFIG
    result = qiime2.sdk.Result.load(input_path)
    if output_format is None:
        if isinstance(result, qiime2.sdk.Artifact):
            output_format = result.format.__name__
        else:
            output_format = 'Visualization'
        result.export_data(output_path)
    else:
        if isinstance(result, qiime2.sdk.Visualization):
            error = '--output-format cannot be used with visualizations'
            click.echo(CONFIG.cfg_style('error', error), err=True)
            click.get_current_context().exit(1)
        else:
            source = result.view(qiime2.sdk.parse_format(output_format))
            if os.path.isfile(str(source)):
                if os.path.isfile(output_path):
                    os.remove(output_path)
                elif os.path.dirname(output_path) == '':
                    # This allows the user to pass a filename as a path if they
                    # want their output in the current working directory
                    output_path = os.path.join('.', output_path)
                if os.path.dirname(output_path) != '':
                    # create directory (recursively) if it doesn't exist yet
                    os.makedirs(os.path.dirname(output_path), exist_ok=True)
                qiime2.util.duplicate(str(source), output_path)
            else:
                distutils.dir_util.copy_tree(str(source), output_path)

    output_type = 'file' if os.path.isfile(output_path) else 'directory'
    success = 'Exported %s as %s to %s %s' % (input_path, output_format,
                                              output_type, output_path)
    click.echo(CONFIG.cfg_style('success', success)) 
Example #28
Source File: util.py    From q2cli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def exit_with_error(e, header='An error has been encountered:',
                    traceback='stderr', status=1):
    import sys
    import traceback as tb
    import textwrap
    import click
    from q2cli.core.config import CONFIG

    footer = []  # footer only exists if traceback is set
    tb_file = None
    if traceback == 'stderr':
        tb_file = sys.stderr
        footer = ['See above for debug info.']
    elif traceback is not None:
        tb_file = traceback
        footer = ['Debug info has been saved to %s' % tb_file.name]

    error = textwrap.indent(str(e), '  ')
    segments = [header, error] + footer

    if traceback is not None:
        tb.print_exception(type(e), e, e.__traceback__, file=tb_file)

        tb_file.write('\n')

    click.echo(CONFIG.cfg_style('error', '\n\n'.join(segments)), err=True)

    if not footer:
        click.echo(err=True)  # extra newline to look normal

    click.get_current_context().exit(status) 
Example #29
Source File: interface.py    From substra with Apache License 2.0 5 votes vote down vote up
def error_printer(fn):
    """Command decorator to pretty print a few selected exceptions from sdk."""
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        ctx = click.get_current_context()
        if ctx.obj.verbose:
            # disable pretty print of errors if verbose mode is activated
            return fn(*args, **kwargs)

        try:
            return fn(*args, **kwargs)
        except exceptions.BadLoginException:
            raise click.ClickException('Login failed: No active account found with the'
                                       ' given credentials.')
        except exceptions.InvalidRequest as e:
            if not isinstance(e.errors, dict):
                raise click.ClickException(f"Request failed: {e.__class__.__name__}: {e}")

            lines = []
            for field, errors in e.errors.items():
                for error in errors:
                    lines.append(f"- {field}: {error}")

            action = fn.__name__.replace('_', ' ')
            pluralized_error = 'errors' if len(lines) > 1 else 'error'
            lines.insert(0, f"Could not {action},"
                            f"the server returned the following {pluralized_error}:")
            raise click.ClickException("\n".join(lines))
        except exceptions.RequestException as e:
            raise click.ClickException(f"Request failed: {e.__class__.__name__}: {e}")
        except (exceptions.ConnectionError,
                exceptions.InvalidResponse,
                exceptions.LoadDataException,
                exceptions.BadConfiguration) as e:
            raise click.ClickException(str(e))

    return wrapper 
Example #30
Source File: extract_lines.py    From kraken with Apache License 2.0 5 votes vote down vote up
def cli(format_type, model, repolygonize, files):
    """
    A small script extracting rectified line polygons as defined in either ALTO or
    PageXML files or run a model to do the same.
    """
    if len(files) == 0:
        ctx = click.get_current_context()
        click.echo(ctx.get_help())
        ctx.exit()

    from PIL import Image
    from os.path import splitext
    from kraken import blla
    from kraken.lib import dataset, segmentation, vgsl

    if model is None:
        for doc in files:
            click.echo(f'Processing {doc} ', nl=False)
            data = dataset.preparse_xml_data([doc], format_type, repolygonize=repolygonize)
            if len(data) > 0:
                bounds = {'type': 'baselines', 'lines': [{'boundary': t['boundary'], 'baseline': t['baseline'], 'text': t['text']} for t in data]}
                for idx, (im, box) in enumerate(segmentation.extract_polygons(Image.open(data[0]['image']), bounds)):
                    click.echo('.', nl=False)
                    im.save('{}.{}.jpg'.format(splitext(data[0]['image'])[0], idx))
                    with open('{}.{}.gt.txt'.format(splitext(data[0]['image'])[0], idx), 'w') as fp:
                        fp.write(box['text'])
    else:
        net = vgsl.TorchVGSLModel.load_model(model)
        for doc in files:
            click.echo(f'Processing {doc} ', nl=False)
            full_im = Image.open(doc)
            bounds = blla.segment(full_im, model=net)
            for idx, (im, box) in enumerate(segmentation.extract_polygons(full_im, bounds)):
                click.echo('.', nl=False)
                im.save('{}.{}.jpg'.format(splitext(doc)[0], idx))