本文整理汇总了Python中click.BadArgumentUsage方法的典型用法代码示例。如果您正苦于以下问题:Python click.BadArgumentUsage方法的具体用法?Python click.BadArgumentUsage怎么用?Python click.BadArgumentUsage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类click
的用法示例。
在下文中一共展示了click.BadArgumentUsage方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_text
# 需要导入模块: import click [as 别名]
# 或者: from click import BadArgumentUsage [as 别名]
def validate_text(ctx, param, value):
conf = click.get_current_context().obj["conf"]
if isinstance(value, tuple):
value = " ".join(value)
if not value and not sys.stdin.isatty():
value = click.get_text_stream("stdin").read()
if value:
value = value.strip()
if conf.character_warning and len(value) > conf.character_warning:
click.confirm("✂ Warning: Tweet is longer than {0} characters. Are you sure?".format(
conf.character_warning), abort=True)
return value
else:
raise click.BadArgumentUsage("Text can’t be empty.")
示例2: parse_run_argument
# 需要导入模块: import click [as 别名]
# 或者: from click import BadArgumentUsage [as 别名]
def parse_run_argument(argument, config, dict_synonyms, mutations_by_file, paths_to_exclude, paths_to_mutate, tests_dirs):
if argument is None:
for path in paths_to_mutate:
for filename in python_source_files(path, tests_dirs, paths_to_exclude):
if filename.startswith('test_') or filename.endswith('__tests.py'):
continue
update_line_numbers(filename)
add_mutations_by_file(mutations_by_file, filename, dict_synonyms, config)
else:
try:
int(argument)
except ValueError:
filename = argument
if not os.path.exists(filename):
raise click.BadArgumentUsage('The run command takes either an integer that is the mutation id or a path to a file to mutate')
update_line_numbers(filename)
add_mutations_by_file(mutations_by_file, filename, dict_synonyms, config)
return
filename, mutation_id = filename_and_mutation_id_from_pk(int(argument))
update_line_numbers(filename)
mutations_by_file[filename] = [mutation_id]
示例3: cli
# 需要导入模块: import click [as 别名]
# 或者: from click import BadArgumentUsage [as 别名]
def cli(packages, virtualenv, python, use_ipython, shell, keep, use_editor, tmpdir, index): # pylint: disable=too-many-arguments
"""Easily try out python packages."""
if not packages:
raise click.BadArgumentUsage("At least one package is required.")
if not shell and use_ipython:
shell = "ipython"
click.echo("==> Use python {0}".format(click.style(python, bold=True)))
if shell:
click.echo("==> Use shell {0}".format(click.style(shell, bold=True)))
click.echo("[*] Downloading packages: {0}".format(click.style(",".join(p.url for p in packages), bold=True)))
try:
envdir = try_packages(packages, virtualenv, python, shell, use_editor, keep, tmpdir, index)
except TryError as error:
click.secho("[*] {0}".format(error), fg="red")
sys.exit(1)
if keep:
click.echo("==> Have a look at the try environment at: {0}".format(envdir))
示例4: sandbox
# 需要导入模块: import click [as 别名]
# 或者: from click import BadArgumentUsage [as 别名]
def sandbox(profile):
prompt_config_overwrite(profile)
# Prompt for user input.
encoded_str = click.prompt('Following instructions from '
'https://metaflow.org/sandbox, '
'please paste the encoded magic string',
type=str)
# Decode the bytes to env_dict.
try:
import base64, zlib
from metaflow.util import to_bytes
env_dict =\
json.loads(zlib.decompress(base64.b64decode(to_bytes(encoded_str))))
except:
# TODO: Add the URL for contact us page in the error?
raise click.BadArgumentUsage('Could not decode the sandbox '\
'configuration. Please contact us.')
# Persist to a file.
persist_env(env_dict, profile)
示例5: resolution
# 需要导入模块: import click [as 别名]
# 或者: from click import BadArgumentUsage [as 别名]
def resolution(resolution, id_, hwid, type_):
"""Change the resolution for the sensor and persist it in the sensor's EEPROM"""
if id_ and (hwid or type_):
raise click.BadArgumentUsage(
"If --id is given --hwid and --type are not allowed."
)
if id_:
try:
sensor = W1ThermSensor.get_available_sensors()[id_ - 1]
except IndexError:
error_msg = (
"No sensor with id {0} available. ".format(id_)
+ "Use the ls command to show all available sensors."
)
if CLICK_MAJOR_VERSION >= 7: # pragma: no cover
raise click.BadOptionUsage("--id", error_msg)
else: # pragma: no cover
raise click.BadOptionUsage(error_msg)
else:
sensor = W1ThermSensor(type_, hwid)
sensor.set_resolution(resolution, persist=True)
示例6: config
# 需要导入模块: import click [as 别名]
# 或者: from click import BadArgumentUsage [as 别名]
def config(ctx, key, value, remove, edit):
"""Get or set config item."""
conf = ctx.obj["conf"]
if not edit and not key:
raise click.BadArgumentUsage("You have to specify either a key or use --edit.")
if edit:
return click.edit(filename=conf.config_file)
if remove:
try:
conf.cfg.remove_option(key[0], key[1])
except Exception as e:
logger.debug(e)
else:
conf.write_config()
return
if not value:
try:
click.echo(conf.cfg.get(key[0], key[1]))
except Exception as e:
logger.debug(e)
return
if not conf.cfg.has_section(key[0]):
conf.cfg.add_section(key[0])
conf.cfg.set(key[0], key[1], value)
conf.write_config()
示例7: validate_config_key
# 需要导入模块: import click [as 别名]
# 或者: from click import BadArgumentUsage [as 别名]
def validate_config_key(ctx, param, value):
"""Validate a configuration key according to `section.item`."""
if not value:
return value
try:
section, item = value.split(".", 1)
except ValueError:
raise click.BadArgumentUsage("Given key does not contain a section name.")
else:
return section, item
示例8: install_command
# 需要导入模块: import click [as 别名]
# 或者: from click import BadArgumentUsage [as 别名]
def install_command(theme, branch, name):
if re.fullmatch('[_\-A-Z0-9a-z]+', theme):
theme_name = name or theme
theme_path = os.path.join(get_themes_dir(), theme_name)
cmd = 'git clone --branch {} ' \
'https://github.com/veripress/themes.git "{}"'.format(theme,
theme_path)
else:
m = re.fullmatch('([_\-A-Z0-9a-z]+)/([_\-A-Z0-9a-z]+)', theme)
if not m:
raise click.BadArgumentUsage(
'The theme should be like "default" '
'(branch of veripress/themes) or "someone/the-theme" '
'(third-party theme on GitHub)'
)
user = m.group(1)
repo = m.group(2)
theme_name = name or repo
theme_path = os.path.join(get_themes_dir(), theme_name)
cmd = 'git clone --branch {} ' \
'https://github.com/{}/{}.git "{}"'.format(branch, user,
repo, theme_path)
print(cmd)
exit_code = os.system(cmd)
if exit_code == 0:
click.echo('\n"{}" theme has been '
'installed successfully.'.format(theme_name))
else:
click.echo('\nSomething went wrong. Do you forget to install git? '
'Or is there another theme with same name existing?')
示例9: is_new_transform
# 需要导入模块: import click [as 别名]
# 或者: from click import BadArgumentUsage [as 别名]
def is_new_transform(ctx, param, value):
try:
if ctx.obj.project.transform_exists(value):
raise click.BadParameter("Transform or module already exists with name {!r}".format(value))
except ValueError as e:
raise click.BadParameter(str(e))
except AssertionError as e:
raise click.BadArgumentUsage(str(e))
return value
示例10: validate_episode
# 需要导入模块: import click [as 别名]
# 或者: from click import BadArgumentUsage [as 别名]
def validate_episode(episode):
src_dir = os.path.join(get_tutorials_dir(), episode)
if not os.path.isdir(src_dir):
raise click.BadArgumentUsage("Episode " + \
click.style("\"{0}\"".format(episode),
fg='red') + " does not exist."\
" To see a list of available episodes, "\
"type:\n" + \
click.style("metaflow tutorials list",
fg='cyan'))
示例11: info
# 需要导入模块: import click [as 别名]
# 或者: from click import BadArgumentUsage [as 别名]
def info(ctx: click.Context, target: str):
"""Display information about the Chaos Toolkit environment.
Available targets are:
* core: display the information about your version of the Chaos Toolkit
* extensions: display the list of installed extensions and plugins
* settings: display your current full settings
"""
if target not in ["core", "settings", "extensions"]:
raise click.BadArgumentUsage("Invalid target")
if target == "core":
fmt = "{:<20}{:<10}"
click.secho(
fmt.format("NAME", "VERSION"),
fg='bright_blue')
click.echo(fmt.format("CLI", __version__))
click.echo(fmt.format("Core library", chaoslib_version))
elif target == "extensions":
fmt = "{:<40}{:<10}{:30}{:50}"
click.secho(
fmt.format("NAME", "VERSION", "LICENSE", "DESCRIPTION"),
fg='bright_blue')
extensions = list_extensions()
for extension in extensions:
summary = extension.summary.replace(
"Chaos Toolkit Extension for ", "")[:50]
click.echo(
fmt.format(
extension.name, extension.version, extension.license,
summary))
elif target == "settings":
settings_path = ctx.obj["settings_path"]
if not os.path.isfile(settings_path):
click.echo("No settings file found at {}".format(settings_path))
return
with open(settings_path) as f:
click.echo(f.read())
示例12: get
# 需要导入模块: import click [as 别名]
# 或者: from click import BadArgumentUsage [as 别名]
def get(id_, hwid, type_, unit, resolution, as_json, offset):
"""Get temperature of a specific sensor"""
if id_ and (hwid or type_):
raise click.BadArgumentUsage(
"If --id is given --hwid and --type are not allowed."
)
if id_:
try:
sensor = W1ThermSensor.get_available_sensors()[id_ - 1]
except IndexError:
error_msg = (
"No sensor with id {0} available. ".format(id_)
+ "Use the ls command to show all available sensors."
)
if CLICK_MAJOR_VERSION >= 7: # pragma: no cover
raise click.BadOptionUsage("--id", error_msg)
else: # pragma: no cover
raise click.BadOptionUsage(error_msg)
else:
sensor = W1ThermSensor(type_, hwid)
if resolution:
sensor.set_resolution(resolution, persist=False)
if offset:
sensor.set_offset(offset, unit)
temperature = sensor.get_temperature(unit)
if as_json:
data = {
"hwid": sensor.id,
"offset": offset,
"type": sensor.name,
"temperature": temperature,
"unit": unit,
}
click.echo(json.dumps(data, indent=4, sort_keys=True))
else:
click.echo(
"Sensor {0} measured temperature: {1} {2}".format(
click.style(sensor.id, bold=True),
click.style(str(temperature), bold=True),
click.style(unit, bold=True),
)
)