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