当前位置: 首页>>代码示例>>Python>>正文


Python click.BadOptionUsage方法代码示例

本文整理汇总了Python中click.BadOptionUsage方法的典型用法代码示例。如果您正苦于以下问题:Python click.BadOptionUsage方法的具体用法?Python click.BadOptionUsage怎么用?Python click.BadOptionUsage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在click的用法示例。


在下文中一共展示了click.BadOptionUsage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: cli

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def cli(*args, **kwargs):
    """
    CSVtoTable commandline utility.
    """
    # Convert CSV file
    content = convert.convert(kwargs["input_file"], **kwargs)

    # Serve the temporary file in browser.
    if kwargs["serve"]:
        convert.serve(content)
    # Write to output file
    elif kwargs["output_file"]:
        # Check if file can be overwrite
        if (not kwargs["overwrite"] and
                not prompt_overwrite(kwargs["output_file"])):
            raise click.Abort()

        convert.save(kwargs["output_file"], content)
        click.secho("File converted successfully: {}".format(
            kwargs["output_file"]), fg="green")
    else:
        # If its not server and output file is missing then raise error
        raise click.BadOptionUsage("Missing argument \"output_file\".") 
开发者ID:vividvilla,项目名称:csvtotable,代码行数:25,代码来源:cli.py

示例2: get_group_info

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def get_group_info(build_info, ci_image_type, groups, versions, full_name, targets):
    if full_name:
        org, image_type, target, version = full_name
        versions = [version]
        targets = [target]
        try:
            groups = [utils.get_group_from_image(image_type, target)]
        except RuntimeError as e:
            raise click.BadOptionUsage(option_name="--full-name", message=e.args[0])
        build_info.set_org(org)
    else:
        image_type = constants.ImageType[ci_image_type]
        if not groups and targets:
            groups = [utils.get_group_from_image(image_type, targets[0])]
    group_info = groupinfo.GroupInfo(
        type_=image_type, names=groups, versions=versions, targets=targets,
    )
    return group_info 
开发者ID:AcademySoftwareFoundation,项目名称:aswf-docker,代码行数:20,代码来源:aswfdocker.py

示例3: resolution

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [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) 
开发者ID:timofurrer,项目名称:w1thermsensor,代码行数:25,代码来源:cli.py

示例4: list_checks

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def list_checks(ruleset, ruleset_file, debug, json, skip, tag, verbose, checks_paths):
    """
    Print the checks.
    """
    if ruleset and ruleset_file:
        raise click.BadOptionUsage(
            "Options '--ruleset' and '--file-ruleset' cannot be used together.")

    try:
        if not debug:
            logging.basicConfig(stream=six.StringIO())

        log_level = _get_log_level(debug=debug,
                                   verbose=verbose)
        checks = get_checks(ruleset_name=ruleset,
                            ruleset_file=ruleset_file,
                            logging_level=log_level,
                            tags=tag,
                            checks_paths=checks_paths,
                            skips=skip)
        _print_checks(checks=checks)

        if json:
            AbstractCheck.save_checks_to_json(file=json, checks=checks)
    except ColinException as ex:
        logger.error("An error occurred: %r", ex)
        if debug:
            raise
        else:
            raise click.ClickException(str(ex))
    except Exception as ex:
        logger.error("An error occurred: %r", ex)
        if debug:
            raise
        else:
            raise click.ClickException(str(ex)) 
开发者ID:user-cont,项目名称:colin,代码行数:38,代码来源:colin.py

示例5: get_filenames_from_template

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def get_filenames_from_template(photo, filename_template, original_name):
    """ get list of export filenames for a photo

    Args:
        photo: a PhotoInfo instance
        filename_template: a PhotoTemplate template string, may be None
        original_name: boolean; if True, use photo's original filename instead of current filename
    
    Returns:
        list of filenames
    
    Raises:
        click.BadOptionUsage if template is invalid
    """
    if filename_template:
        photo_ext = pathlib.Path(photo.original_filename).suffix
        filenames, unmatched = photo.render_template(filename_template, path_sep="_")
        if not filenames or unmatched:
            raise click.BadOptionUsage(
                "filename_template",
                f"Invalid template '{filename_template}': results={filenames} unmatched={unmatched}",
            )
        filenames = [f"{file_}{photo_ext}" for file_ in filenames]
    else:
        filenames = [photo.original_filename] if original_name else [photo.filename]
    return filenames 
开发者ID:RhetTbull,项目名称:osxphotos,代码行数:28,代码来源:__main__.py

示例6: main

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def main(pid=None, verbose=False):
    level = logging.DEBUG if verbose else logging.INFO
    configure_logging(level=level)
    sock = None
    if pid is None:
        pid, sock = connect_first_available_server()
    if pid is None:
        raise click.BadOptionUsage('pid', "Server PID is required!")
    shell = BackdoorShell(pid, sock=sock)
    shell.interact() 
开发者ID:anyant,项目名称:rssant,代码行数:12,代码来源:shell.py

示例7: separator_type

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def separator_type(sep):
    if len(sep) != 1:
        raise click.BadOptionUsage(option_name='separator',
                                   message='separator can only be a char')
    if sep == unit_char:
        raise click.BadOptionUsage(option_name='separator',
                                   message='separator can not be `\\` ')
    return sep 
开发者ID:alingse,项目名称:jsoncsv,代码行数:10,代码来源:main.py

示例8: metric

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def metric(ctx, **kwargs):
    """Compute metrics"""

    verbose = ctx.obj["verbose"]

    if kwargs["from"] not in registered_readers.keys():
        raise click.BadOptionUsage(
            "from",
            "Cannot read from format '{}'".format(kwargs["from"])
        )

    if kwargs["input"] is None:
        raise click.BadOptionUsage(
            "input",
            "--input must be provided."
        )

    from_reader_name = kwargs["from"]

    try:
        MetricComputer(
            registered_reader_class=_load(registered_readers, from_reader_name),
            input_path=kwargs["input"],
            output_format=kwargs["to"],
            output_path=kwargs["output"],
            by_feeder=kwargs["feeder"],
        ).compute()
    except Exception as e:
        # TODO: discuss whether we should raise exception here?
        sys.exit(1)  # TODO: Set error code based on exception
    else:
        sys.exit(0) 
开发者ID:NREL,项目名称:ditto,代码行数:34,代码来源:cli.py

示例9: _user_args_to_dict

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def _user_args_to_dict(user_list):
    # Similar function in mlflow.cli is throwing exception on import
    user_dict = {}
    for s in user_list:
        try:
            name, value = s.split('=')
        except ValueError:
            # not enough values to unpack
            raise click.BadOptionUsage("config", "Config options must be a pair and should be"
                                                 "provided as ``-C key=value`` or "
                                                 "``--config key=value``")
        if name in user_dict:
            raise click.ClickException("Repeated parameter: '{}'".format(name))
        user_dict[name] = value
    return user_dict 
开发者ID:mlflow,项目名称:mlflow,代码行数:17,代码来源:cli.py

示例10: clip

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def clip(bounds, reference, **kwargs):
    if not bounds and not reference:
        raise click.BadOptionUsage("One of --bounds or --reference must be supplied.")
    if not bounds:
        bounds = spatial.import_bounds(reference)
    elevation.clip(bounds, **kwargs) 
开发者ID:bopen,项目名称:elevation,代码行数:8,代码来源:cli.py

示例11: audit

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def audit(anchore_config, ctx, image, imagefile, include_allanchore):
    """
    Image IDs can be specified as hash ids, repo names (e.g. centos), or tags (e.g. centos:latest).
    """

    global config, imagelist, nav
    ecode = 0
    success = True
    config = anchore_config

    #include_allanchore = True

    if image and imagefile:
        raise click.BadOptionUsage('Can only use one of --image, --imagefile')

    #if image or imagefile:
    #    include_allanchore = False

    try:
        imagedict = build_image_list(anchore_config, image, imagefile, not (image or imagefile), include_allanchore)
        imagelist = imagedict.keys()
        try:
            ret = anchore_utils.discover_imageIds(imagelist)
        except ValueError as err:
            raise err
        else:
            imagelist = ret

    except Exception as err:
        anchore_print_err("could not load input images")
        sys.exit(1) 
开发者ID:anchore,项目名称:anchore,代码行数:33,代码来源:audit.py

示例12: kelnerd

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def kelnerd(
        ctx,
        load_model,
        extract,
        engine,
        input_node,
        output_node,
        host,
        port,
        dry_run
):
    """ Serves Keras and Tensorflow models """
    ctx.obj = {}
    from . import models

    flags = []
    if extract:
        flags += ['EXTRACT']

    if engine == 'keras':
        loaded_model = models.keras_model.load(
            load_model, input_node, output_node, flags=flags
        )
    else:
        loaded_model = models.tensorflow_model.load(
            load_model, input_node, output_node, flags=flags
        )

    ctx.obj['model'] = loaded_model

    if ctx.invoked_subcommand is None:

        if engine == 'tensorflow':
            if input_node is None or output_node is None:
                raise click.BadOptionUsage('Serving Tensorflow models' +
                                           ' required input and output nodes' +
                                           ' to be specified', ctx)

        try:
            k_server = server.KelnerServer(loaded_model)
            click.echo('Listening on %s:%d' % (host, port), err=True)
            if not dry_run:
                k_server.serve_http(host, port)

        except OSError as e:
            click.echo(str(e), err=True) 
开发者ID:lunardog,项目名称:kelner,代码行数:48,代码来源:cli.py

示例13: get_dirnames_from_template

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def get_dirnames_from_template(photo, directory, export_by_date, dest, dry_run):
    """ get list of directories to export a photo into, creates directories if they don't exist

    Args:
        photo: a PhotoInstance object
        directory: a PhotoTemplate template string, may be None
        export_by_date: boolean; if True, creates output directories in form YYYY-MM-DD
        dest: top-level destination directory
        dry_run: boolean; if True, runs in dry-run mode and does not create output directories

    Returns:
        list of export directories

    Raises:
        click.BadOptionUsage if template is invalid
    """

    if export_by_date:
        date_created = DateTimeFormatter(photo.date)
        dest_path = os.path.join(
            dest, date_created.year, date_created.mm, date_created.dd
        )
        if not (dry_run or os.path.isdir(dest_path)):
            os.makedirs(dest_path)
        dest_paths = [dest_path]
    elif directory:
        # got a directory template, render it and check results are valid
        dirnames, unmatched = photo.render_template(directory)
        if not dirnames:
            raise click.BadOptionUsage(
                "directory",
                f"Invalid template '{directory}': results={dirnames} unmatched={unmatched}",
            )
        elif unmatched:
            raise click.BadOptionUsage(
                "directory",
                f"Invalid template '{directory}': results={dirnames} unmatched={unmatched}",
            )
        dest_paths = []
        for dirname in dirnames:
            dirname = sanitize_filepath(dirname, platform="auto")
            dest_path = os.path.join(dest, dirname)
            if not is_valid_filepath(dest_path, platform="auto"):
                raise ValueError(f"Invalid file path: '{dest_path}'")
            if not dry_run and not os.path.isdir(dest_path):
                os.makedirs(dest_path)
            dest_paths.append(dest_path)
    else:
        dest_paths = [dest]
    return dest_paths 
开发者ID:RhetTbull,项目名称:osxphotos,代码行数:52,代码来源:__main__.py

示例14: add_composite_traintuple

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def add_composite_traintuple(ctx, algo_key, dataset_key, data_samples, head_model_key,
                             trunk_model_key, out_trunk_model_permissions, tag, metadata):
    """Add composite traintuple.

    The option --data-samples-path must point to a valid JSON file with the
    following schema:

    \b
    {
        "keys": list[str],
    }

    \b
    Where:
    - keys: list of data sample keys

    The option --out-trunk-model-permissions-path must point to a valid JSON file with the
    following schema:

    \b
    {
        "authorized_ids": list[str],
    }
    """

    if head_model_key and not trunk_model_key:
        raise click.BadOptionUsage('--trunk-model-key',
                                   "The --trunk-model-key option is required when using "
                                   "--head-model-key.")
    if trunk_model_key and not head_model_key:
        raise click.BadOptionUsage('--head-model-key',
                                   "The --head-model-key option is required when using "
                                   "--trunk-model-key.")

    client = get_client(ctx.obj)
    data = {
        'algo_key': algo_key,
        'data_manager_key': dataset_key,
        'in_head_model_key': head_model_key,
        'in_trunk_model_key': trunk_model_key,
    }

    if data_samples:
        data['train_data_sample_keys'] = load_data_samples_keys(data_samples)

    if out_trunk_model_permissions:
        data['out_trunk_model_permissions'] = out_trunk_model_permissions

    if tag:
        data['tag'] = tag

    if metadata:
        data['metadata'] = metadata
    res = client.add_composite_traintuple(data)
    printer = printers.get_asset_printer(assets.COMPOSITE_TRAINTUPLE, ctx.obj.output_format)
    printer.print(res, is_list=False) 
开发者ID:SubstraFoundation,项目名称:substra,代码行数:58,代码来源:interface.py

示例15: run_local

# 需要导入模块: import click [as 别名]
# 或者: from click import BadOptionUsage [as 别名]
def run_local(algo, train_opener, test_opener, metrics, rank,
              train_data_samples, test_data_samples, inmodels,
              fake_data_samples):
    """Run local.

    Train and test the algo located in ALGO (directory or archive) locally.

    This command can be used to check that objective, dataset and algo assets
    implementations are compatible.

    It will execute sequentially 3 tasks in docker:

    \b
    - train algo using train data samples
    - test model using test data samples
    - get model perf

    \b
    It will create several output files:
    - sandbox/model/model
    - sandbox/pred_test/perf.json
    - sandbox/pred_test/pred
    """
    if fake_data_samples and (train_data_samples or test_data_samples):
        raise click.BadOptionUsage('--fake-data-samples',
                                   'Options --train-data-samples and --test-data-samples cannot '
                                   'be used if --fake-data-samples is activated')
    if not fake_data_samples and not train_data_samples and not test_data_samples:
        raise click.BadOptionUsage('--fake-data-samples',
                                   'Missing option --fake-data-samples or --test-data-samples '
                                   'and --train-data-samples')
    if not fake_data_samples and train_data_samples and not test_data_samples:
        raise click.BadOptionUsage('--test-data-samples',
                                   'Missing option --test-data-samples')
    if not fake_data_samples and not train_data_samples and test_data_samples:
        raise click.BadOptionUsage('--train-data-samples',
                                   'Missing option --train-data-samples')

    try:
        runner.compute(algo_path=algo,
                       train_opener_file=train_opener,
                       test_opener_file=test_opener,
                       metrics_path=metrics,
                       train_data_path=train_data_samples,
                       test_data_path=test_data_samples,
                       fake_data_samples=fake_data_samples,
                       rank=rank,
                       inmodels=inmodels)
    except runner.PathTraversalException as e:
        raise click.ClickException(
            f'Archive "{e.archive_path}" includes at least 1 file or folder '
            f'located outside the archive root folder: "{e.issue_path}"'
        ) 
开发者ID:SubstraFoundation,项目名称:substra,代码行数:55,代码来源:interface.py


注:本文中的click.BadOptionUsage方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。