我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用click.BadArgumentUsage()。
def _filter_by_test_name(pipelines, test_name): """ Shrinks given pipelines so that they have only a single test inside. :param pipelines: a dict of pipelines to filter :param test_name: name of the test to remain in pipelines :return: dictionary of pipelines """ if not test_name: # --all-tests return pipelines filtered = {} for pipe, tests in pipelines.items(): for test in tests: if test.__name__ == test_name: filtered[pipe] = [test] if not filtered: raise click.BadArgumentUsage('Test "{}" not found'.format(test_name)) return filtered
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) 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?')
def main(account, type, filter, verbose, git_options, existing_only): """Console script for clone_army""" if account.startswith('-'): raise click.BadArgumentUsage("Options for Git should come at end.") if verbose: logging.getLogger(__name__).setLevel(logging.INFO) if existing_only: if account or (type == 'user'): raise click.exceptions.BadArgumentUsage( 'Do not specify account or type with --existing-only') else: clone_army.Repository.synch_present(filter) else: if not account: raise click.exceptions.BadArgumentUsage('Missing account name') clone_army.Repository.synch_all(account, type, filter, *git_options)
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.")
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))
def generate(app, force, no_optimize, verbose, quiet): """ app: this will be resolved to os.getcwd()/{app}.yml """ logging.basicConfig(level=logging.WARN + 10 * quiet - 10 * verbose) cwd = os.getcwd() this_dir = os.path.dirname(os.path.realpath(__file__)) templates_dir = os.path.join(this_dir, u"templates") yaml_raw_data = read_yaml_file(os.path.join(cwd, YAML_FILENAME)) for one_raw_app in yaml_raw_data.get(YamlSchemaKeywords.APPS): if one_raw_app.get(YamlSchemaKeywords.APP_NAME) == app: target_app = one_raw_app break else: raise click.BadArgumentUsage(u"App not found") normalized_data = normalize_schema(target_app) app_target_path = os.path.join(cwd, app) if os.path.exists(app_target_path): if force: logger.info(u"Deleting {}".format(app_target_path)) shutil.rmtree(app_target_path) else: raise click.ClickException(u'Path: %s already exists.' % click.format_filename(app_target_path)) structure_of_app = get_structure(normalized_data) app_generator = TemplateFileAppGenerator(cwd, templates_dir, normalized_data, structure_of_app) logger.info(u"Generating app") app_generator.generate_app() if not no_optimize: logger.info(u"Optimizing source code") app_generator.optimize_source_codes() click.echo(u'Done')
def _verify_paths(ctx, param, items): bad_paths = [i for i in items if not os.path.exists(i)] if bad_paths: message = u'could not find following paths:\n{}'.format('\n'.join( bad_paths)) raise click.BadArgumentUsage(message) return items
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()
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
def count_words(path_to_lesson): """Count words ignoring code.""" path = Path(path_to_lesson) if not path.exists() or not path.is_file(): raise click.BadArgumentUsage("The path should be a markdown file") with path.open('r') as fp: content = fp.read() word_count = utils.count_words( markdown.markdown(content, extensions=['gfm'])) click.echo("Word count: {}".format( click.style(str(word_count), fg='green')))
def serve(base_directory): global repository if repository is None: if base_directory is None: raise click.BadArgumentUsage("Please specify a base directory.") repository = FilesystemRepository(pathlib.Path(base_directory)) HocrViewerApplication(app).run()
def config(ctx, config, all_): """Get/set configuration on the NCP""" click.secho( "NOTE: Configuration changes do not persist across resets", fg='red' ) if config and all_: raise click.BadOptionUsage("Specify a config or --all, not both") if not (config or all_): raise click.BadOptionUsage("One of config or --all must be specified") s = yield from util.setup(ctx.obj['device'], ctx.obj['baudrate'], util.print_cb) if all_: for config in t.EzspConfigId: v = yield from s.getConfigurationValue(config) if v[0] == t.EzspStatus.ERROR_INVALID_ID: continue click.echo("%s=%s" % (config.name, v[1])) s.close() return if '=' in config: config, value = config.split("=", 1) if config.isdigit(): try: config = t.EzspConfigId(int(config)) except ValueError: raise click.BadArgumentUsage("Invalid config ID: %s" % ( config, )) else: try: config = t.EzspConfigId[config] except KeyError: raise click.BadArgumentUsage("Invalid config name: %s" % ( config, )) try: value = t.uint16_t(value) if not (0 <= value <= 65535): raise ValueError("%s out of allowed range 0..65535" % ( value, )) except ValueError as e: raise click.BadArgumentUsage("Invalid value: %s" % (e, )) v = yield from s.setConfigurationValue(config, value) click.echo(v) s.close() return v = yield from s.getConfigurationValue(config) click.echo(v)