本文整理汇总了Python中click.Context方法的典型用法代码示例。如果您正苦于以下问题:Python click.Context方法的具体用法?Python click.Context怎么用?Python click.Context使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类click
的用法示例。
在下文中一共展示了click.Context方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_command
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def get_command(self, ctx: click.Context, name: str) -> click.Command:
"""Return the relevant command given the context and name.
.. warning::
This differs substantially from Flask in that it allows
for the inbuilt commands to be overridden.
"""
info = ctx.ensure_object(ScriptInfo)
command = None
try:
command = info.load_app().cli.get_command(ctx, name)
except NoAppException:
pass
if command is None:
command = super().get_command(ctx, name)
return command
示例2: test_input_file_invalid_ip_addresses_passsed
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def test_input_file_invalid_ip_addresses_passsed(self, api_client):
"""Error returned if only invalid IP addresses are passed in input file."""
runner = CliRunner()
expected = (
"Error: at least one valid IP address must be passed either as an "
"argument (IP_ADDRESS) or through the -i/--input_file option."
)
result = runner.invoke(
subcommand.interesting,
["-i", StringIO("not-an-ip")],
parent=Context(main, info_name="greynoise"),
)
assert result.exit_code == -1
assert "Usage: greynoise interesting" in result.output
assert expected in result.output
api_client.interesting.assert_not_called()
示例3: test_empty_input_file
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def test_empty_input_file(self, api_client):
"""Error is returned if empty input fle is passed."""
runner = CliRunner()
expected = (
"Error: at least one query must be passed either as an argument "
"(QUERY) or through the -i/--input_file option."
)
result = runner.invoke(
subcommand.query,
["-i", StringIO()],
parent=Context(main, info_name="greynoise"),
)
assert result.exit_code == -1
assert "Usage: greynoise query" in result.output
assert expected in result.output
api_client.query.assert_not_called()
示例4: check_subsampling_params
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def check_subsampling_params(ctx: Context, argument: Argument, value) -> Any:
subsampling = ctx.params.get('subsampling')
if not subsampling and value is not None:
tpl = 'This parameter ({}) only applies to subsampling, to enable it add `--subsampling` to your command'
app_logger.error(tpl.format(argument.name))
ctx.abort()
if argument.name == 'subsampling_log' and subsampling and value is None:
app_logger.error('''In order to perform subsampling you need to specify whether to log1p input counts or not:
to do this specify in your command as --subsampling-log [true|false]''')
ctx.abort()
defaults = {
'subsampling_num_pc': 100,
'subsampling_num_cells': None
}
if subsampling and value is None:
return defaults.get(argument.name, None)
return value
示例5: metadata
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def metadata(
ctx: click.Context,
output_file: typing.Optional[typing.IO[str]],
target: typing.List[str],
):
"""
Get metadata from a given endpoint
"""
client = Client(*ctx.obj["args"], **ctx.obj["kwargs"])
metadata = {
k: v.to_dict() for k, v in client.get_metadata(targets=target).items() # type: ignore
}
if output_file:
json.dump(metadata, output_file)
click.secho(f"Saved metadata json to file: '{output_file}'")
else:
pprint(metadata)
return metadata
示例6: download_model
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def download_model(ctx: click.Context, output_dir: str, target: typing.List[str]):
"""
Download the actual model from the target and write to an output directory
"""
client = Client(*ctx.obj["args"], **ctx.obj["kwargs"])
models = client.download_model(targets=target)
# Iterate over mapping of models and save into their own sub dirs of the output_dir
for model_name, model in models.items():
model_out_dir = os.path.join(output_dir, model_name)
os.mkdir(model_out_dir)
click.secho(
f"Writing model '{model_name}' to directory: '{model_out_dir}'...", nl=False
)
serializer.dump(model, model_out_dir)
click.secho(f"done")
click.secho(f"Wrote all models to directory: {output_dir}", fg="green")
示例7: check_version
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def check_version(ctx, _, value):
"""
Print current version, and check for latest version.
Called via 'geocube --version'
:param ctx: Application context object (click.Context)
:param value: Passed in by Click
:return None
"""
if not value or ctx.resilient_parsing:
return
click.echo(f"geocube v{__version__}")
ctx.exit()
示例8: test_customized_cli
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def test_customized_cli():
cli = ProfilingCLI(default='bar')
@cli.command(aliases=['fooo', 'foooo'])
def foo():
pass
@cli.command()
@click.argument('l', default='answer')
@click.option('-n', type=int, default=0)
def bar(l, n=0):
click.echo('%s: %d' % (l, n))
assert len(cli.commands) == 2
ctx = click.Context(cli)
assert cli.get_command(ctx, 'foo').name == 'foo'
assert cli.get_command(ctx, 'fooo').name == 'foo'
assert cli.get_command(ctx, 'foooo').name == 'foo'
assert cli.get_command(ctx, 'bar').name == 'bar'
assert cli.get_command(ctx, 'hello.txt').name == 'bar'
assert 'Usage:' in cli_runner.invoke(cli, []).output
assert cli_runner.invoke(cli, ['zero']).output == 'zero: 0\n'
assert cli_runner.invoke(cli, ['one', '-n', '1']).output == 'one: 1\n'
assert cli_runner.invoke(cli, ['-n', '42']).output == 'answer: 42\n'
assert 'no such option' in cli_runner.invoke(cli, ['-x']).output
示例9: cli_option_traceback
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def cli_option_traceback(func):
"""Decorator for adding a pre-defined, reusable CLI option `--traceback`."""
# noinspection PyUnusedLocal
def _callback(ctx: click.Context, param: click.Option, value: bool):
ctx_obj = ctx.ensure_object(dict)
if ctx_obj is not None:
ctx_obj["traceback"] = value
return value
return click.option(
'--traceback',
is_flag=True,
help="Enable tracing back errors by dumping the Python call stack. "
"Pass as very first option to also trace back error during command-line validation.",
callback=_callback)(func)
示例10: validate
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def validate(ctx: click.Context, source: str,
no_verify_tls: bool = False) -> Experiment:
"""Validate the experiment at SOURCE."""
settings = load_settings(ctx.obj["settings_path"])
try:
experiment = load_experiment(
source, settings, verify_tls=not no_verify_tls)
except InvalidSource as x:
logger.error(str(x))
logger.debug(x)
ctx.exit(1)
try:
notify(settings, ValidateFlowEvent.ValidateStarted, experiment)
ensure_experiment_is_valid(experiment)
notify(settings, ValidateFlowEvent.ValidateCompleted, experiment)
logger.info("experiment syntax and semantic look valid")
except ChaosException as x:
notify(settings, ValidateFlowEvent.ValidateFailed, experiment, x)
logger.error(str(x))
logger.debug(x)
ctx.exit(1)
return experiment
示例11: set_settings_value
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def set_settings_value(ctx: click.Context, key: str, value: str = None):
"""
Set a settings value.
The value must be a valid JSON string so that it can be interpreted
with the appropriate type.
The key must be dotted path to its location in the settings file.
"""
if not os.path.isfile(ctx.obj["settings_path"]):
ctx.exit(1)
settings = load_settings(ctx.obj["settings_path"]) or {}
item = locate_settings_entry(settings, key)
if not item:
ctx.exit(1)
parent, entry, key_tail, index = item
value = json.loads(value)
if key_tail is not None:
parent[key_tail] = value
elif index is not None:
parent[index] = value
save_settings(settings, ctx.obj["settings_path"])
示例12: get_settings_value
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def get_settings_value(ctx: click.Context, key: str, fmt: str = "json"):
"""
Show a settings value.
The key must be dotted path to its location in the settings file.
"""
if not os.path.isfile(ctx.obj["settings_path"]):
ctx.exit(1)
settings = load_settings(ctx.obj["settings_path"]) or {}
item = locate_settings_entry(settings, key)
if not item:
ctx.exit(1)
parent, entry, key_tail, index = item
if fmt == "json":
click.echo(json.dumps(entry, indent=2))
elif fmt == "string":
click.echo(str(entry))
elif fmt == "yaml":
click.echo(yaml.dump(entry, indent=2))
示例13: discover
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def discover(ctx: click.Context, package: str,
discovery_path: str = "./discovery.json",
no_system_info: bool = False,
no_install: bool = False) -> Discovery:
"""Discover capabilities and experiments."""
settings = load_settings(ctx.obj["settings_path"])
try:
notify(settings, DiscoverFlowEvent.DiscoverStarted, package)
discovery = disco(
package_name=package, discover_system=not no_system_info,
download_and_install=not no_install)
except DiscoveryFailed as err:
notify(settings, DiscoverFlowEvent.DiscoverFailed, package, err)
logger.debug("Failed to discover {}".format(package), exc_info=err)
logger.fatal(str(err))
return
with open(discovery_path, "w") as d:
d.write(json.dumps(discovery, indent=2, default=encoder))
logger.info("Discovery outcome saved in {p}".format(
p=discovery_path))
notify(settings, DiscoverFlowEvent.DiscoverCompleted, discovery)
return discovery
示例14: VOC
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def VOC(ctx: click.Context, **kwargs: Any) -> None:
kwargs.update(ctx.obj['common'])
model, _ = ctx.obj['model'], ctx.obj['params']
config = model.config
im_size = config.input_size
class2idx = efficientdet.data.voc.LABEL_2_IDX
im_size = config.input_size
ds = efficientdet.data.voc.build_dataset(
kwargs['root_test'],
im_input_size=im_size,
shuffle=False)
ds = ds.padded_batch(batch_size=kwargs['batch_size'],
padded_shapes=((*im_size, 3),
((None,), (None, 4))),
padding_values=(0., (-1, -1.)))
gtCOCO = coco.tf_data_to_COCO(ds, class2idx)
coco.evaluate(
model=model,
dataset=ds,
steps=sum(1 for _ in ds),
gtCOCO=gtCOCO)
示例15: _launch_agents
# 需要导入模块: import click [as 别名]
# 或者: from click import Context [as 别名]
def _launch_agents(
click_context: click.core.Context, agents: List[str], multithreaded: bool
) -> None:
"""
Run multiple agents.
:param click_context: click context object.
:param agents: agents names.
:param multithreaded: bool flag to run as multithreads.
:return: None.
"""
agents_directories = list(map(Path, list(OrderedDict.fromkeys(agents))))
if multithreaded:
failed = _launch_threads(click_context, agents_directories)
else:
failed = _launch_subprocesses(click_context, agents_directories)
logger.debug(f"Exit cli. code: {failed}")
sys.exit(failed)