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


Python click.Parameter方法代码示例

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


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

示例1: sanitize_version

# 需要导入模块: import click [as 别名]
# 或者: from click import Parameter [as 别名]
def sanitize_version(_ctx: Optional[click.Context],
                     _param: Optional[Union[click.Option, click.Parameter]],
                     value: str
                     ) -> str:
    """Sanitize a version number by stripping git tag ref and leading "v".

    To be used as the callback of a click option or parameter.

    Args:
        ctx: Click context object.
        param: The click option or parameter the callback is being used with.
        value: Value passed to the option or parameter from the CLI.

    Returns:
        str: The SemVer version number.

    """
    version = value.replace('refs/tags/', '')  # strip git ref
    if version.startswith('v'):  # strip leading "v"
        version = version[1:]
    if VersionInfo.isvalid(version):  # valid SemVer
        return version
    raise ValueError(f'version of "{version}" does not follow SemVer') 
开发者ID:onicagroup,项目名称:runway,代码行数:25,代码来源:update_urls.py

示例2: set_defaults_from_config

# 需要导入模块: import click [as 别名]
# 或者: from click import Parameter [as 别名]
def set_defaults_from_config(
    context: click.Context, param: click.Parameter, value: Union[str, int],
) -> Path:
    supplied_paths = context.params.get("path")

    search_paths = supplied_paths
    if not search_paths:
        search_paths = (".",)

    project_root = find_project_root([Path(path) for path in search_paths])
    file_config = read_config_toml(project_root, CONFIG_FILE)
    if file_config:
        config_path = project_root / "pyproject.toml"
    else:
        config_path = None
    context.params["config_path"] = config_path
    file_config = apply_multi_defaults(file_config, context.params)

    if context.default_map is None:
        context.default_map = {}

    context.default_map.update(file_config)
    return project_root 
开发者ID:darrenburns,项目名称:ward,代码行数:25,代码来源:config.py

示例3: test_read_pyproject_toml

# 需要导入模块: import click [as 别名]
# 或者: from click import Parameter [as 别名]
def test_read_pyproject_toml(self) -> None:
        test_toml_file = THIS_DIR / "test.toml"

        # Fake a click context and parameter so mypy stays happy
        class FakeContext(click.Context):
            def __init__(self) -> None:
                self.default_map: Dict[str, Any] = {}

        class FakeParameter(click.Parameter):
            def __init__(self) -> None:
                pass

        fake_ctx = FakeContext()
        black.read_pyproject_toml(
            fake_ctx, FakeParameter(), str(test_toml_file),
        )
        config = fake_ctx.default_map
        self.assertEqual(config["verbose"], "1")
        self.assertEqual(config["check"], "no")
        self.assertEqual(config["diff"], "y")
        self.assertEqual(config["color"], "True")
        self.assertEqual(config["line_length"], "79")
        self.assertEqual(config["target_version"], ["py36", "py37", "py38"])
        self.assertEqual(config["exclude"], r"\.pyi?$")
        self.assertEqual(config["include"], r"\.py?$") 
开发者ID:psf,项目名称:black,代码行数:27,代码来源:test_black.py

示例4: _param_get_config

# 需要导入模块: import click [as 别名]
# 或者: from click import Parameter [as 别名]
def _param_get_config(_: Context, param: Parameter, config_file: Optional[_FilePath]) -> Config:  # pragma: no cover
    try:
        return get_config(config_file)
    except Exception as ex:
        raise BadParameter(
            f'{ex}\n\tUse the "server config check" command for an analyse.',
            param=param
        ) from ex 
开发者ID:k4cg,项目名称:nichtparasoup,代码行数:10,代码来源:server_run.py

示例5: validate_address

# 需要导入模块: import click [as 别名]
# 或者: from click import Parameter [as 别名]
def validate_address(
    _ctx: click.Context, _param: click.Parameter, value: Optional[str]
) -> Optional[Address]:
    if value is None:
        # None as default value allowed
        return None
    if not is_checksum_address(value):
        raise click.BadParameter("not an EIP-55 checksummed address")
    return to_canonical_address(value) 
开发者ID:raiden-network,项目名称:raiden-services,代码行数:11,代码来源:cli.py

示例6: validate_address

# 需要导入模块: import click [as 别名]
# 或者: from click import Parameter [as 别名]
def validate_address(
    _: Context, _param: Union[Option, Parameter], value: Optional[str]
) -> Optional[ChecksumAddress]:
    if not value:
        return None
    try:
        is_address(value)
        return to_checksum_address(value)
    except ValueError:
        raise click.BadParameter("must be a valid ethereum address") 
开发者ID:raiden-network,项目名称:raiden-contracts,代码行数:12,代码来源:__main__.py

示例7: error_removed_option

# 需要导入模块: import click [as 别名]
# 或者: from click import Parameter [as 别名]
def error_removed_option(message: str) -> Callable:
    """ Takes a message and returns a callback that raises NoSuchOption

    if the value is not None. The message is used as an argument to NoSuchOption. """

    def f(_: Any, param: Parameter, value: Any) -> None:
        if value is not None:
            raise click.NoSuchOption(
                f'--{param.name.replace("_", "-")} is no longer a valid option. ' + message
            )

    return f 
开发者ID:raiden-network,项目名称:raiden-contracts,代码行数:14,代码来源:__main__.py

示例8: read_pyproject_toml

# 需要导入模块: import click [as 别名]
# 或者: from click import Parameter [as 别名]
def read_pyproject_toml(
    ctx: click.Context, _param: click.Parameter, value: str
) -> Optional[str]:
    if not value:
        root_path = ctx.params.get("repo_path", None)
        if not root_path:
            root_path = "."
        root_path = pathlib.Path(root_path).resolve()
        config_path = root_path / "pyproject.toml"
        if config_path.is_file():
            value = str(config_path)
        else:
            config_path = root_path / "tartufo.toml"
            if config_path.is_file():
                value = str(config_path)
            else:
                return None
    try:
        toml_file = toml.load(value)
        config = toml_file.get("tool", {}).get("tartufo", {})
    except (toml.TomlDecodeError, OSError) as exc:
        raise click.FileError(
            filename=str(config_path),
            hint="Error reading configuration file: {}".format(exc),
        )
    if not config:
        return None
    if ctx.default_map is None:
        ctx.default_map = {}
    ctx.default_map.update(  # type: ignore
        {k.replace("--", "").replace("-", "_"): v for k, v in config.items()}
    )
    return str(value) 
开发者ID:godaddy,项目名称:tartufo,代码行数:35,代码来源:config.py

示例9: get_install_completion_arguments

# 需要导入模块: import click [as 别名]
# 或者: from click import Parameter [as 别名]
def get_install_completion_arguments() -> Tuple[click.Parameter, click.Parameter]:
    install_param, show_param = get_completion_inspect_parameters()
    click_install_param, _ = get_click_param(install_param)
    click_show_param, _ = get_click_param(show_param)
    return click_install_param, click_show_param 
开发者ID:tiangolo,项目名称:typer,代码行数:7,代码来源:main.py

示例10: get_callback

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

示例11: __init__

# 需要导入模块: import click [as 别名]
# 或者: from click import Parameter [as 别名]
def __init__(
        self,
        *,
        name: str,
        default: Any = inspect.Parameter.empty,
        annotation: Any = inspect.Parameter.empty,
    ) -> None:
        self.name = name
        self.default = default
        self.annotation = annotation 
开发者ID:tiangolo,项目名称:typer,代码行数:12,代码来源:models.py

示例12: install_callback

# 需要导入模块: import click [as 别名]
# 或者: from click import Parameter [as 别名]
def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
    if not value or ctx.resilient_parsing:
        return value  # pragma no cover
    if isinstance(value, str):
        shell, path = install(shell=value)
    else:
        shell, path = install()
    click.secho(f"{shell} completion installed in {path}", fg="green")
    click.echo("Completion will take effect once you restart the terminal")
    sys.exit(0) 
开发者ID:tiangolo,项目名称:typer,代码行数:12,代码来源:completion.py

示例13: get_param_callback

# 需要导入模块: import click [as 别名]
# 或者: from click import Parameter [as 别名]
def get_param_callback(
    *, callback: Optional[Callable] = None, convertor: Optional[Callable] = None
) -> Optional[Callable]:
    if not callback:
        return None
    parameters = get_params_from_function(callback)
    ctx_name = None
    click_param_name = None
    value_name = None
    untyped_names: List[str] = []
    for param_name, param_sig in parameters.items():
        if lenient_issubclass(param_sig.annotation, click.Context):
            ctx_name = param_name
        elif lenient_issubclass(param_sig.annotation, click.Parameter):
            click_param_name = param_name
        else:
            untyped_names.append(param_name)
    # Extract value param name first
    if untyped_names:
        value_name = untyped_names.pop()
    # If context and Click param were not typed (old/Click callback style) extract them
    if untyped_names:
        if ctx_name is None:
            ctx_name = untyped_names.pop(0)
        if click_param_name is None:
            if untyped_names:
                click_param_name = untyped_names.pop(0)
        if untyped_names:
            raise click.ClickException(
                "Too many CLI parameter callback function parameters"
            )

    def wrapper(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
        use_params: Dict[str, Any] = {}
        if ctx_name:
            use_params[ctx_name] = ctx
        if click_param_name:
            use_params[click_param_name] = param
        if value_name:
            if convertor:
                use_value = convertor(value)
            else:
                use_value = value
            use_params[value_name] = use_value
        return callback(**use_params)  # type: ignore

    update_wrapper(wrapper, callback)
    return wrapper 
开发者ID:tiangolo,项目名称:typer,代码行数:50,代码来源:main.py


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