本文整理匯總了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')
示例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
示例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?$")
示例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
示例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)
示例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")
示例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
示例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)
示例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
示例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
示例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
示例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)
示例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