How to use the click.ClickException function in click

To help you get started, we’ve selected a few click examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github fedora-infra / fedora-messaging / fedora_messaging / cli.py View on Github external
Raises:
        click.ClickException: If the object cannot be loaded.

    Returns:
        callable: The callable object.
    """
    callback_path = callback or config.conf["callback"]
    if not callback_path:
        raise click.ClickException(
            "A Python path to a callable object that accepts the message must be provided"
            ' with the "--callback" command line option or in the configuration file'
        )
    try:
        module, cls = callback_path.strip().split(":")
    except ValueError:
        raise click.ClickException(
            "Unable to parse the callback path ({}); the "
            'expected format is "my_package.module:'
            'callable_object"'.format(callback_path)
        )
    try:
        module = importlib.import_module(module)
    except ImportError as e:
        provider = "--callback argument" if callback else "configuration file"
        raise click.ClickException(
            "Failed to import the callback module ({}) provided in the {}".format(
                str(e), provider
            )
        )

    try:
        callback_object = getattr(module, cls)
github grow / grow / grow / commands / subcommands / run.py View on Github external
config = env.EnvConfig(host=host, port=port, name=env.Name.DEV,
                           scheme=scheme, cached=False, dev=True)
    environment = env.Env(config)
    pod = pods.Pod(
        root, storage=storage.FileStorage, env=environment)
    if deployment:
        deployment_obj = pod.get_deployment(deployment)
        pod.set_env(deployment_obj.config.env)
    if not ui:
        pod.disable(pod.FEATURE_UI)
    try:
        manager.start(pod, host=host, port=port, open_browser=browser,
                      debug=debug, preprocess=preprocess,
                      update_check=update_check)
    except pods.Error as e:
        raise click.ClickException(str(e))
    except KeyboardInterrupt:
        pass  # Let the normal process work when doing keyboard inturrupt.
    return pod
github druids / developers-chamber / developers_chamber / ecs_utils.py View on Github external
def update_service_to_new_task_definition(cluster, service, task_definition, region, force=True, ecs_client=None):
    ecs_client = ecs_client if ecs_client else _get_ecs_client(region)

    try:
        response = ecs_client.update_service(
            cluster=cluster,
            service=service,
            taskDefinition=task_definition,
            forceNewDeployment=force,
        )
    except ecs_client.exceptions.ClusterNotFoundException:
        raise ClickException("Cluster not found: '{}'".format(cluster))
    except ecs_client.exceptions.ServiceNotFoundException:
        raise ClickException("Service not found: '{}'".format(service))
    except ClientError as ex:
        raise ClickException(ex)
github iiasa / ixmp / ixmp / cli.py View on Github external
def import_scenario(context, file, discard_solution, add_units, init_items,
                    commit_steps):
    """Import scenario data."""
    scenario = context['scen']

    if scenario.has_solution() and discard_solution:
        scenario.remove_solution()

    try:
        scenario.check_out()
    except ValueError as e:
        raise click.ClickException(e.args[0])  # Show exception message to user
    except RuntimeError as e:
        if 'not yet saved' in e.args[0]:
            pass  # --version=new; no need to check out
        else:  # pragma: no cover
            raise

    scenario.read_excel(
        Path(file),
        add_units=add_units,
        init_items=init_items,
        commit_steps=commit_steps,
    )
github SFDO-Tooling / CumulusCI / cumulusci / cli / cci.py View on Github external
except TaskOptionsError as e:
            exception = click.UsageError(e.message)
            handle_exception_debug(config, debug, e, throw_exception=exception)
        except ApexTestException as e:
            exception = click.ClickException('Failed: ApexTestException')
            handle_exception_debug(config, debug, e, throw_exception=exception)
        except BrowserTestFailure as e:
            exception = click.ClickException('Failed: BrowserTestFailure')
            handle_exception_debug(config, debug, e, throw_exception=exception)
        except MetadataComponentFailure as e:
            exception = click.ClickException(
                'Failed: MetadataComponentFailure'
            )
            handle_exception_debug(config, debug, e, throw_exception=exception)
        except MetadataApiError as e:
            exception = click.ClickException('Failed: MetadataApiError')
            handle_exception_debug(config, debug, e, throw_exception=exception)
        except ScratchOrgException as e:
            exception = click.ClickException(
                'ScratchOrgException: {}'.format(e.message)
            )
            handle_exception_debug(config, debug, e, throw_exception=exception)
        except Exception as e:
            handle_exception_debug(config, debug, e, no_prompt=no_prompt)

    # Delete the scratch org if --delete-org was set
    if delete_org:
        try:
            org_config.delete_org()
        except Exception as e:
            click.echo(
                'Scratch org deletion failed.  Ignoring the error below to complete the flow:')
github achillean / shodan-python / shodan / cli / alert.py View on Github external
def alert_list(expired):
    """List all the active alerts"""
    key = get_api_key()

    # Get the list
    api = shodan.Shodan(key)
    try:
        results = api.alerts(include_expired=expired)
    except shodan.APIError as e:
        raise click.ClickException(e.value)

    if len(results) > 0:
        click.echo(u'# {:14} {:<21} {:<15s}'.format('Alert ID', 'Name', 'IP/ Network'))

        for alert in results:
            click.echo(
                u'{:16} {:<30} {:<35} '.format(
                    click.style(alert['id'], fg='yellow'),
                    click.style(alert['name'], fg='cyan'),
                    click.style(', '.join(alert['filters']['ip']), fg='white')
                ),
                nl=False
            )

            if 'triggers' in alert and alert['triggers']:
                click.secho('Triggers: ', fg='magenta', nl=False)
github EUDAT-B2SHARE / b2share / b2share / modules / schemas / cli.py View on Github external
def community_schema_list_block_schema_versions(verbose, community, version=None):
    """Show the block schema versions in the community schema element of a
        specific community"""
    comm = get_community_by_name_or_id(community)
    if not comm:
        raise click.BadParameter("There is no community by this name or ID: %s"%
                                 community)
    community_schema = CommunitySchema.get_community_schema(comm.id, version)
    if not community_schema:
        raise click.ClickException("""Community %s does not have a community
            schema""" % comm.name)
    community_schema_dict = json.loads(community_schema.community_schema)
    props = community_schema_dict['properties']
    click.secho("""The following block schema versions are listed for community
        %s, community schema version %s""" % (
            comm.name,
            "latest %d" % community_schema.version if not version else version))
    for key in props:
        click.secho("Block schema: %s, version url: %s" % (
            key, props[key]['$ref']))
github kblomqvist / yasha / yasha / cli.py View on Github external
tests   = dict()
    filters = dict()
    parsers = dict()
    classes = []

    try:
        module = load_python_module(file)
    except NameError as e:
        msg = 'Unable to load extensions, {}'
        raise ClickException(msg.format(e))
    except SyntaxError as e:
        msg = "Unable to load extensions\n{} ({}, line {})"
        error = e.msg[0].upper() + e.msg[1:]
        filename = os.path.relpath(e.filename)
        raise ClickException(msg.format(error, filename, e.lineno))

    for attr in [getattr(module, x) for x in dir(module)]:
        if inspect.isfunction(attr):
            if attr.__name__.startswith('test_'):
                name = attr.__name__[5:]
                tests[name] = attr
            if attr.__name__.startswith('filter_'):
                name = attr.__name__[7:]
                filters[name] = attr
            if attr.__name__.startswith('parse_'):
                name = attr.__name__[6:]
                parsers['.' + name] = attr
        if inspect.isclass(attr):
            if issubclass(attr, Extension):
                classes.append(attr)
github projecthamster / hamster-cli / hamster_cli / hamster_cli.py View on Github external
def _cancel(controler):
    """
    Cancel tracking current temporary fact, discaring the result.

    Returns:
        None: If success.

    Raises:
        KeyErŕor: No *ongoing fact* can be found.
    """
    try:
        controler.facts.cancel_tmp_fact()
    except KeyError:
        message = _("Nothing tracked right now. Not doing anything.")
        controler.client_logger.info(message)
        raise click.ClickException(message)
    else:
        message = _("Tracking canceled.")
        click.echo(message)
        controler.client_logger.debug(message)
github icgc / icgc-get / icgcget / cli.py View on Github external
def check_code(client, code):
    if code != 0:
        logger.error("{} client exited with a nonzero error code {}.".format(client, code))
        raise click.ClickException("Please check client output for error messages")