Python click.BadArgumentUsage() Examples

The following are 12 code examples of click.BadArgumentUsage(). 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: helper.py    From twtxt with MIT License 6 votes vote down vote up
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.") 
Example #3
Source File: __main__.py    From mutmut with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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] 
Example #4
Source File: __main__.py    From try with MIT License 6 votes vote down vote up
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)) 
Example #5
Source File: main_cli.py    From metaflow with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: cli.py    From twtxt with MIT License 5 votes vote down vote up
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() 
Example #7
Source File: helper.py    From twtxt with MIT License 5 votes vote down vote up
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 
Example #8
Source File: theme.py    From veripress with MIT License 5 votes vote down vote up
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?') 
Example #9
Source File: framework.py    From canari3 with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #10
Source File: main_cli.py    From metaflow with Apache License 2.0 5 votes vote down vote up
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')) 
Example #11
Source File: cli.py    From chaostoolkit with Apache License 2.0 4 votes vote down vote up
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()) 
Example #12
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),
            )
        )