Python click.BadOptionUsage() Examples

The following are 18 code examples of click.BadOptionUsage(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module click , or try the search function .
Example #1
Source File: cli.py    From w1thermsensor with MIT License 7 votes vote down vote up
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) 
Example #2
Source File: cli.py    From csvtotable with MIT License 6 votes vote down vote up
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\".") 
Example #3
Source File: aswfdocker.py    From aswf-docker with Apache License 2.0 6 votes vote down vote up
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 
Example #4
Source File: shell.py    From rssant with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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() 
Example #5
Source File: main.py    From jsoncsv with Apache License 2.0 5 votes vote down vote up
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 
Example #6
Source File: cli.py    From ditto with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #7
Source File: colin.py    From colin with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #8
Source File: cli.py    From mlflow with Apache License 2.0 5 votes vote down vote up
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 
Example #9
Source File: cli.py    From elevation with Apache License 2.0 5 votes vote down vote up
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) 
Example #10
Source File: __main__.py    From osxphotos with MIT License 5 votes vote down vote up
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 
Example #11
Source File: audit.py    From anchore with Apache License 2.0 5 votes vote down vote up
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) 
Example #12
Source File: __main__.py    From osxphotos with MIT License 4 votes vote down vote up
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 
Example #13
Source File: interface.py    From substra with Apache License 2.0 4 votes vote down vote up
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) 
Example #14
Source File: interface.py    From substra with Apache License 2.0 4 votes vote down vote up
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}"'
        ) 
Example #15
Source File: common.py    From anchore with Apache License 2.0 4 votes vote down vote up
def build_image_list(config, image, imagefile, all_local, include_allanchore, dockerfile=None, exclude_file=None):
    """Given option inputs from the cli, construct a list of image ids. Includes all found with no exclusion logic"""

    if not image and not (imagefile or all_local):
        raise click.BadOptionUsage('No input found for image source. One of <image>, <imagefile>, or <all> must be specified')

    if image and imagefile:
        raise click.BadOptionUsage('Only one of <image> and <imagefile> can be specified')

    filter_images = []
    if exclude_file:
        with open(exclude_file) as f:
            for line in f.readlines():
                filter_images.append(line.strip())

    imagelist = {}
    if image:
        imagelist[image] = {'dockerfile':dockerfile}

    if imagefile:
        filelist = anchore_utils.read_kvfile_tolist(imagefile)
        for i in range(len(filelist)):
            l = filelist[i]
            imageId = l[0]
            try:
                dfile = l[1]
            except:
                dfile = None
            imagelist[imageId] = {'dockerfile':dfile}

    if all_local:
        docker_cli = contexts['docker_cli']
        if docker_cli:
            for f in docker_cli.images(all=True, quiet=True, filters={'dangling': False}):
                if f not in imagelist and f not in filter_images:
                    imagelist[f] = {'dockerfile':None}
        else:
            raise Exception("Could not load any images from local docker host - is docker running?")

    if include_allanchore:
        ret = contexts['anchore_db'].load_all_images().keys()
        if ret and len(ret) > 0:
            for l in list(set(imagelist.keys()) | set(ret)):
                imagelist[l] = {'dockerfile':None}

    # Remove excluded items
    for excluded in filter_images:
        docker_cli = contexts['docker_cli']
        if not docker_cli:
            raise Exception("Could not query docker - is docker running?")
        for img in docker_cli.images(name=excluded, quiet=True):
            imagelist.pop(img, None)

    return imagelist 
Example #16
Source File: query.py    From anchore with Apache License 2.0 4 votes vote down vote up
def query(anchore_config, image, imagefile, include_allanchore, module):
    """
    Image IDs can be specified as hash ids, repo names (e.g. centos), or tags (e.g. centos:latest).

    Execute the specified query (module) with any parameters it requires. Modules are scripts in a specific location.

    Each query has its own parameters and outputs.

    Examples using pre-defined queries:

    'anchore query --image nginx:latest list-packages all'
    'anchore query has-package wget'
    'anchore query --image nginx:latest list-files-detail all'
    'anchore query cve-scan all'

    """

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

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

        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.keys()
                imagelist = ret

        except Exception as err:
            anchore_print_err("could not load input images")
            sys.exit(1)

    try:
        nav = init_nav_contexts()

        result = nav.run_query(list(module))
        if result:
            anchore_utils.print_result(config, result)

        if nav.check_for_warnings(result):
            ecode = 2

    except:
        anchore_print_err("query operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode) 
Example #17
Source File: cli.py    From w1thermsensor with MIT License 4 votes vote down vote up
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),
            )
        ) 
Example #18
Source File: cli.py    From kelner with MIT License 4 votes vote down vote up
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)