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


Python click.BadParameter方法代码示例

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


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

示例1: valid_int_gt_zero

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def valid_int_gt_zero(ctx, param, value):
    """ Validator for integers > 0 (value >= 1)"""
    def _validator(param, value):
        try:
            value = int(value)
        except Exception as e:
            raise click.BadParameter('%s must be integer above zero: %s'
                                     % (param.metavar, e.message))
        if value <= 0:
            raise click.BadParameter('%s must be an integer above zero'
                                     % param.metavar)
        return value

    if param.multiple:
        return [_validator(param, v) for v in value]
    else:
        return _validator(param, value)


# CLI ARGUMENTS 
开发者ID:ceholden,项目名称:yatsm,代码行数:22,代码来源:options.py

示例2: arg_date

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def arg_date(var='date', metavar='<date>', date_frmt_key='date_frmt'):
    def _arg_date(f):
        def callback(ctx, param, value):
            try:
                value = dt.strptime(value, ctx.params[date_frmt_key])
            except KeyError:
                raise click.ClickException(
                    'Need to use `date_format_opt` when using `date_arg`')
            except ValueError:
                raise click.BadParameter(
                    'Cannot parse {v} to date with format {f}'.format(
                        v=value, f=ctx.params['date_frmt']))
            else:
                return value
        return click.argument(var, metavar=metavar, callback=callback)(f)
    return _arg_date 
开发者ID:ceholden,项目名称:yatsm,代码行数:18,代码来源:options.py

示例3: arg_job_number

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def arg_job_number(f):
    def callback(ctx, param, value):
        try:
            value = int(value)
        except:
            raise click.BadParameter('Must specify an integer >= 0')

        if value < 0:
            raise click.BadParameter('Must specify an integer >= 0')
        elif value == 0:
            return value
        else:
            return value - 1

    return click.argument('job_number', nargs=1, callback=callback,
                          metavar='<job_number>')(f)


# CLI OPTIONS 
开发者ID:ceholden,项目名称:yatsm,代码行数:21,代码来源:options.py

示例4: opt_exampleimg

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
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) 
开发者ID:ceholden,项目名称:yatsm,代码行数:23,代码来源:options.py

示例5: opt_resultdir

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
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 
开发者ID:ceholden,项目名称:yatsm,代码行数:26,代码来源:options.py

示例6: validate_headers

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def validate_headers(
    ctx: click.core.Context, param: click.core.Parameter, raw_value: Tuple[str, ...]
) -> Dict[str, str]:
    headers = {}
    for header in raw_value:
        with reraise_format_error(header):
            key, value = header.split(":", maxsplit=1)
        value = value.lstrip()
        key = key.strip()
        if not key:
            raise click.BadParameter("Header name should not be empty")
        if not utils.is_latin_1_encodable(key):
            raise click.BadParameter("Header name should be latin-1 encodable")
        if not utils.is_latin_1_encodable(value):
            raise click.BadParameter("Header value should be latin-1 encodable")
        if utils.has_invalid_characters(key, value):
            raise click.BadParameter("Invalid return character or leading space in header")
        headers[key] = value
    return headers 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:21,代码来源:callbacks.py

示例7: main

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def main(contract, market):
    exporter = Exporter()

    if all((contract, market)):
        raise click.BadParameter('Either contract or market must be specified')
    elif not any((contract, market)):
        raise click.BadParameter('Neither contract nor market is specified')

    pd.options.display.max_rows = 1000

    if contract:
        try:
            meta = exporter.lookup(code=contract)
        except FinamObjectNotFoundError:
            logger.info('No such contract')
        else:
            print(meta)
    else:
        contracts = exporter.lookup(market=Market[market])
        print(contracts) 
开发者ID:ffeast,项目名称:finam-export,代码行数:22,代码来源:finam-lookup.py

示例8: validate_scanner_list

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def validate_scanner_list(ctx, param, value):
    """
    Validate a comma-separated list of scanners and extract it into a list of groups and IDs.
    """
    if not value:
        return None

    valid_groups = ctx.obj.scanner_groups
    scanners = [x.strip() for x in value.split(',')]

    if 'all' in scanners:
        return ['all']

    scanner_ids = []
    for scanner in scanners:
        if scanner.isdigit():
            scanner_ids.append(scanner)
        elif scanner in valid_groups:
            scanner_ids += ctx.obj.scanner_group_map[scanner]
        else:
            raise click.BadParameter('Invalid scanner "{0}" provided. Must be a valid group or numeric ID.'
                                     .format(scanner))

    return scanner_ids 
开发者ID:Grunny,项目名称:zap-cli,代码行数:26,代码来源:helpers.py

示例9: validate_profile

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def validate_profile(self, ctx, param, value_colored):
    if value_colored is None: return value_colored

    value_nocolor = decolorize(value_colored)

    # check if in list
    if value_nocolor not in self.profile_list_nocolors:
      import click
      err_m = 'Profile "%s" (decolored to "%s") is not from ~/.aws/credentials file.'%(value_colored, value_nocolor)
      raise click.BadParameter(err_m)

    # set the profile in an env var so that boto3 picks it up automatically
    if value_nocolor is not None:
      import os
      os.environ['AWS_PROFILE'] = value_nocolor

    # save profile in click context for other usage in displayed/emailed report
    ctx.obj['aws_profile'] = value_nocolor

    # save in last-used profile file
    self.last_profile_cls.set(value_nocolor)

    # done
    return value_nocolor 
开发者ID:autofitcloud,项目名称:isitfit,代码行数:26,代码来源:utils.py

示例10: create_transifexrc

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def create_transifexrc(transifex_username, transifex_password):
    """
    Create `$HOME/.transifexrc`
    """
    target = os.path.normpath(os.path.expanduser('~/.transifexrc'))

    if os.path.exists(target):
        click.echo('{0} already exists, skipped.'.format(target))
        return

    if not transifex_username or not 'transifex_password':
        msg = textwrap.dedent("""\
        You need transifex username/password by command option or environment.
        command option: --transifex-username, --transifex-password
        """)
        raise click.BadParameter(msg, param_hint='transifex_username,transifex_password')

    with open(target, 'wt') as rc:
        rc.write(TRANSIFEXRC_TEMPLATE % locals())
    click.echo('Create: {0}'.format(target)) 
开发者ID:sphinx-doc,项目名称:sphinx-intl,代码行数:22,代码来源:transifex.py

示例11: read_config

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def read_config(path, passed_tags):

    tags = Tags()
    passed_tags = sum(passed_tags, ())
    for tag in passed_tags:
        tags.add(tag)

    namespace = {
        "__file__": os.path.abspath(path),
        "tags": tags,
    }

    olddir = os.getcwd()
    try:
        if not os.path.isfile(path):
            msg = "'%s' is not found (or specify --locale-dir option)." % path
            raise click.BadParameter(msg)
        os.chdir(os.path.dirname(path) or ".")
        execfile_(os.path.basename(path), namespace)
    finally:
        os.chdir(olddir)

    return namespace 
开发者ID:sphinx-doc,项目名称:sphinx-intl,代码行数:25,代码来源:commands.py

示例12: export_

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def export_(
    short_name, provider, publish, tag, dataverse_server, dataverse_name
):
    """Export data to 3rd party provider."""
    try:
        output = export_dataset(
            short_name=short_name,
            provider=provider,
            publish=publish,
            tag=tag,
            handle_access_token_fn=prompt_access_token,
            handle_tag_selection_fn=prompt_tag_selection,
            dataverse_server_url=dataverse_server,
            dataverse_name=dataverse_name,
        )
    except (
        ValueError, InvalidAccessToken, DatasetNotFound, requests.HTTPError
    ) as e:
        raise click.BadParameter(e)

    click.echo(output)
    click.secho('OK', fg='green') 
开发者ID:SwissDataScienceCenter,项目名称:renku-python,代码行数:24,代码来源:dataset.py

示例13: init

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def init(cloud_url):
    """
    Choose a cloud server to use. Sets CLOUD_URL as the cloud server to use and
    sets up replication of global databases from that cloud server if a local
    database is already initialized (via `openag db init`).
    """
    old_cloud_url = config["cloud_server"]["url"]
    if old_cloud_url and old_cloud_url != cloud_url:
        raise click.ClickException(
            'Server "{}" already selected. Call `openag cloud deinit` to '
            'detach from that server before selecting a new one'.format(
                old_cloud_url
            )
        )
    parsed_url = urlparse(cloud_url)
    if not parsed_url.scheme or not parsed_url.netloc or not parsed_url.port:
        raise click.BadParameter("Invalid url")
    if config["local_server"]["url"]:
        utils.replicate_global_dbs(cloud_url=cloud_url)
    config["cloud_server"]["url"] = cloud_url 
开发者ID:OpenAgricultureFoundation,项目名称:openag_python,代码行数:22,代码来源:db.py

示例14: test_curve_parameters

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def test_curve_parameters(self):
        '''Test curve parameter.'''
        param = cli.Curve()
        self.assertRaises(click.BadParameter, param.convert,
                          value='', param=None, ctx=None)
        self.assertRaises(click.BadParameter, param.convert,
                          value='{}', param=None, ctx=None)
        missing_tau = '{"beta0": 0.017, "beta1": -0.023, "beta2": 0.24}'
        self.assertRaises(click.BadParameter, param.convert,
                          value=missing_tau, param=None, ctx=None)
        self.assertEqual(self.y1,
                         param.convert(json.dumps(asdict(self.y1)),
                                       None, None))
        self.assertEqual(self.y2,
                         param.convert(json.dumps(asdict(self.y2)),
                                       None, None)) 
开发者ID:luphord,项目名称:nelson_siegel_svensson,代码行数:18,代码来源:test_nelson_siegel_svensson.py

示例15: test_float_array_parameters

# 需要导入模块: import click [as 别名]
# 或者: from click import BadParameter [as 别名]
def test_float_array_parameters(self):
        '''Test float array parameter.'''
        param = cli.FloatArray()
        self.assertRaises(click.BadParameter, param.convert,
                          value='', param=None, ctx=None)
        self.assertRaises(click.BadParameter, param.convert,
                          value='{"a": 1}', param=None, ctx=None)
        self.assertRaises(click.BadParameter, param.convert,
                          value='["a"]', param=None, ctx=None)
        self.assertEqual(np.array([1.0]),
                         param.convert('[1.0]', None, None))
        self.assertEqual(np.array([1.0]),
                         param.convert('[1]', None, None))
        self.assertEqual([],
                         param.convert('[]', None, None).tolist())
        self.assertTrue((np.array([1.0, 2.0, 3.0]) ==
                         param.convert('[1,   2,3.0]', None, None)).all()) 
开发者ID:luphord,项目名称:nelson_siegel_svensson,代码行数:19,代码来源:test_nelson_siegel_svensson.py


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