当前位置: 首页>>代码示例>>Python>>正文


Python click.UsageError方法代码示例

本文整理汇总了Python中click.UsageError方法的典型用法代码示例。如果您正苦于以下问题:Python click.UsageError方法的具体用法?Python click.UsageError怎么用?Python click.UsageError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在click的用法示例。


在下文中一共展示了click.UsageError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: check_databases

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def check_databases(ds):
    # Run check_connection against every connected database
    # to confirm they are all usable
    for database in list(ds.databases.values()):
        try:
            await database.execute_fn(check_connection)
        except SpatialiteConnectionProblem:
            raise click.UsageError(
                "It looks like you're trying to load a SpatiaLite"
                " database without first loading the SpatiaLite module."
                "\n\nRead more: https://datasette.readthedocs.io/en/latest/spatialite.html"
            )
        except ConnectionProblem as e:
            raise click.UsageError(
                "Connection to {} failed check: {}".format(
                    database.path, str(e.args[0])
                )
            ) 
开发者ID:simonw,项目名称:datasette,代码行数:20,代码来源:cli.py

示例2: convert

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def convert(self, value, param, ctx):
        if value:
            date = self._parse_multiformat(value)
            if date is None:
                raise click.UsageError(
                    "Could not match value '{}' to any supported date format"
                    .format(value)
                )
            # When we parse a date, we want to parse it in the timezone
            # expected by the user, so that midnight is midnight in the local
            # timezone, not in UTC. Cf issue #16.
            date.tzinfo = tz.tzlocal()
            # Add an offset to match the week beginning specified in the
            # configuration
            if param.name == "week":
                week_start = ctx.obj.config.get(
                    "options", "week_start", "monday")
                date = apply_weekday_offset(
                    start_time=date, week_start=week_start)
            return date 
开发者ID:TailorDev,项目名称:Watson,代码行数:22,代码来源:cli.py

示例3: _configure_bigquery

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def _configure_bigquery(credentials_file, credentials_blob, api_max_connections=None):
    if credentials_file is None and credentials_blob is None:
        raise click.UsageError(
            "Must pass either --credentials-file or --credentials-blob"
        )
    elif credentials_file is not None and credentials_blob is not None:
        raise click.UsageError(
            "Cannot pass both --credentials-file and --credentials-blob"
        )
    elif credentials_file is not None:
        logger.debug("Configuring BigQuery from %r", credentials_file.name)
        credentials = json.load(credentials_file)
    else:
        logger.debug("Configuring BigQuery from base64 blob")
        credentials = json.loads(credentials_blob)

    return BigQuery(
        credentials["client_email"],
        credentials["private_key"],
        max_connections=api_max_connections,
    ) 
开发者ID:pypa,项目名称:linehaul,代码行数:23,代码来源:cli.py

示例4: roles_add_permissions

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def roles_add_permissions(role, permissions):
    """Add permissions to role.

    Role is an existing role name.
    Permissions are a comma separated list.
    """
    role = _datastore._prepare_role_modify_args(role)
    if role is None:
        raise click.UsageError("Cannot find role.")
    if _datastore.add_permissions_to_role(role, permissions):
        click.secho(
            f'Permission(s) "{permissions}" added to role "{role.name}" successfully.',
            fg="green",
        )
    else:  # pragma: no cover
        raise click.UsageError("Cannot add permission(s) to role.") 
开发者ID:Flask-Middleware,项目名称:flask-security,代码行数:18,代码来源:cli.py

示例5: validate_lang

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def validate_lang(ctx, param, lang):
    """Validation callback for the <lang> option.
    Ensures <lang> is a supported language unless the <nocheck> flag is set
    """
    if ctx.params['nocheck']:
        return lang

    try:
        if lang not in tts_langs():
            raise click.UsageError(
                "'%s' not in list of supported languages.\n"
                "Use --all to list languages or "
                "add --nocheck to disable language check." % lang)
        else:
            # The language is valid.
            # No need to let gTTS re-validate.
            ctx.params['nocheck'] = True
    except RuntimeError as e:
        # Only case where the <nocheck> flag can be False
        # Non-fatal. gTTS will try to re-validate.
        log.debug(str(e), exc_info=True)

    return lang 
开发者ID:luoliyan,项目名称:chinese-support-redux,代码行数:25,代码来源:cli.py

示例6: csv2model

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def csv2model(cls, csv_path):
        with open(csv_path) as csvfile:
            spamreader = csv.reader(csvfile)

            Model = None
            for row in spamreader:
                if spamreader.line_num == 1:
                    continue
                if len(row) == 1 or row[0] == ''.join(row):
                    if Model is not None:
                        yield Model
                    Model = cls.gen_model(row[0])
                elif len(row) == 8:
                    row = cls.row_processing(row)
                    if row.type != cls.TYPE_REF:
                        Model.columns.append(row)
                    else:
                        Model.refs.append(row)
                else:
                    raise click.UsageError(
                        click.style(f'csv file err: `{row}`.', fg='red'))
            yield Model 
开发者ID:TTWShell,项目名称:hobbit-core,代码行数:24,代码来源:bootstrap.py

示例7: profiler_arguments

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def profiler_arguments(f):
    @click.argument('argv', nargs=-1)
    @click.option('-m', 'module', type=Module(),
                  help='Run library module as a script.')
    @click.option('-c', 'command', type=Command(),
                  help='Program passed in as string.')
    @wraps(f)
    def wrapped(argv, module, command, **kwargs):
        if module is not None and command is not None:
            raise click.UsageError('Option -m and -c are exclusive')
        script = module or command
        if script is None:
            # -m and -c not passed.
            try:
                script_filename, argv = argv[0], argv[1:]
            except IndexError:
                raise click.UsageError('Script not specified')
            script = Script().convert(script_filename, None, None)
        kwargs.update(script=script, argv=argv)
        return f(**kwargs)
    return wrapped 
开发者ID:what-studio,项目名称:profiling,代码行数:23,代码来源:__main__.py

示例8: check_arguments

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def check_arguments(fortran_library, components, float_type, burnin, timesteps, **kwargs):
    fortran_version = check_fortran_library(fortran_library)

    if 'fortran' in components or 'fortran-mpi' in components:
        if not fortran_library:
            raise click.UsageError('Path to fortran library must be given when running fortran components')
        if not fortran_version:
            raise click.UsageError('Fortran library failed to import')

    if fortran_version != 'parallel' and 'fortran-mpi' in components:
        raise click.UsageError('Fortran library must be compiled with MPI support for fortran-mpi component')

    if float_type != 'float64' and ('fortran' in components or 'fortran-mpi' in components):
        raise click.UsageError('Can run Fortran components only with "float64" float type')

    if not burnin < timesteps:
        raise click.UsageError('burnin must be smaller than number of timesteps') 
开发者ID:team-ocean,项目名称:veros,代码行数:19,代码来源:run_benchmarks.py

示例9: resolve_command

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def resolve_command(self, ctx, args):
        """Override clicks ``resolve_command`` method
        and appends *Did you mean ...* suggestions
        to the raised exception message.
        """
        try:
            return super(AliasedGroup, self).resolve_command(ctx, args)
        except click.exceptions.UsageError as error:
            error_msg = str(error)
            original_cmd_name = click.utils.make_str(args[0])
            matches = difflib.get_close_matches(
                original_cmd_name,
                self.list_commands(ctx),
                self.max_suggestions,
                self.cutoff)
            if matches:
                error_msg += '\n\nDid you mean one of these?\n    {0}'.format(
                    '\n    '.join(matches))
            raise click.exceptions.UsageError(error_msg, error.ctx) 
开发者ID:cloudify-cosmo,项目名称:cloudify-cli,代码行数:21,代码来源:cfy.py

示例10: parent

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def parent(ctx, input, depth):
    """Takes a [x, y, z] tile as input and writes its parent to stdout
    in the same form.

    $ echo "[486, 332, 10]" | mercantile parent

    Output:

    [243, 166, 9]
    """
    src = normalize_input(input)
    for line in iter_lines(src):
        tile = json.loads(line)[:3]
        if tile[2] - depth < 0:
            raise click.UsageError("Invalid parent level: {0}".format(tile[2] - depth))
        for i in range(depth):
            tile = mercantile.parent(tile)
        output = json.dumps(tile)
        click.echo(output) 
开发者ID:enricofer,项目名称:go2mapillary,代码行数:21,代码来源:__init__.py

示例11: shell

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def shell(runtime, script=None, python=None):
    # alias for backwards-compatibility
    variables = {
        "config": runtime,
        "runtime": runtime,
        "project_config": runtime.project_config,
    }

    if script:
        if python:
            raise click.UsageError("Cannot specify both --script and --python")
        runpy.run_path(script, init_globals=variables)
    elif python:
        exec(python, variables)
    else:
        code.interact(local=variables) 
开发者ID:SFDO-Tooling,项目名称:CumulusCI,代码行数:18,代码来源:cci.py

示例12: org_scratch

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def org_scratch(runtime, config_name, org_name, default, devhub, days, no_password):
    runtime.check_org_overwrite(org_name)

    scratch_configs = getattr(runtime.project_config, "orgs__scratch")
    if not scratch_configs:
        raise click.UsageError("No scratch org configs found in cumulusci.yml")
    scratch_config = scratch_configs.get(config_name)
    if not scratch_config:
        raise click.UsageError(
            f"No scratch org config named {config_name} found in the cumulusci.yml file"
        )

    if devhub:
        scratch_config["devhub"] = devhub

    runtime.keychain.create_scratch_org(
        org_name, config_name, days, set_password=not (no_password)
    )

    if default:
        runtime.keychain.set_default_org(org_name)
        click.echo(f"{org_name} is now the default org")
    else:
        click.echo(f"{org_name} is configured for use") 
开发者ID:SFDO-Tooling,项目名称:CumulusCI,代码行数:26,代码来源:cci.py

示例13: test_task_run_invalid_option

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def test_task_run_invalid_option(self):
        runtime = mock.Mock()
        runtime.get_org.return_value = (None, None)
        runtime.project_config.get_task.return_value = TaskConfig(
            {"class_path": "cumulusci.cli.tests.test_cci.DummyTask"}
        )

        with self.assertRaises(click.UsageError):
            run_click_command(
                cci.task_run,
                runtime=runtime,
                task_name="test",
                org=None,
                o=[("bogus", "blue")],
                debug=False,
                debug_before=False,
                debug_after=False,
                no_prompt=True,
            ) 
开发者ID:SFDO-Tooling,项目名称:CumulusCI,代码行数:21,代码来源:test_cci.py

示例14: test_flow_run_delete_non_scratch

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def test_flow_run_delete_non_scratch(self,):
        org_config = mock.Mock(scratch=False)
        runtime = mock.Mock()
        runtime.get_org.return_value = ("test", org_config)

        with self.assertRaises(click.UsageError):
            run_click_command(
                cci.flow_run,
                runtime=runtime,
                flow_name="test",
                org="test",
                delete_org=True,
                debug=False,
                o=None,
                skip=(),
                no_prompt=True,
            ) 
开发者ID:SFDO-Tooling,项目名称:CumulusCI,代码行数:19,代码来源:test_cci.py

示例15: execute_query_against_remote

# 需要导入模块: import click [as 别名]
# 或者: from click import UsageError [as 别名]
def execute_query_against_remote(host, query, variables):
    parsed_url = urlparse(host)
    if not (parsed_url.scheme and parsed_url.netloc):
        raise click.UsageError(
            'Host {host} is not a valid URL. Host URL should include scheme ie http://localhost'.format(
                host=host
            )
        )

    sanity_check = requests.get(urljoin(host, '/dagit_info'))
    sanity_check.raise_for_status()
    if 'dagit' not in sanity_check.text:
        raise click.UsageError(
            'Host {host} failed sanity check. It is not a dagit server.'.format(host=host)
        )

    response = requests.post(
        urljoin(host, '/graphql'), params={'query': query, 'variables': variables}
    )
    response.raise_for_status()
    str_res = response.json()
    return str_res 
开发者ID:dagster-io,项目名称:dagster,代码行数:24,代码来源:cli.py


注:本文中的click.UsageError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。