當前位置: 首頁>>代碼示例>>Python>>正文


Python click.BadArgumentUsage方法代碼示例

本文整理匯總了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.") 
開發者ID:buckket,項目名稱:twtxt,代碼行數:18,代碼來源:helper.py

示例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] 
開發者ID:boxed,項目名稱:mutmut,代碼行數:24,代碼來源:__main__.py

示例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)) 
開發者ID:timofurrer,項目名稱:try,代碼行數:23,代碼來源:__main__.py

示例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) 
開發者ID:Netflix,項目名稱:metaflow,代碼行數:21,代碼來源:main_cli.py

示例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) 
開發者ID:timofurrer,項目名稱:w1thermsensor,代碼行數:25,代碼來源:cli.py

示例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() 
開發者ID:buckket,項目名稱:twtxt,代碼行數:33,代碼來源:cli.py

示例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 
開發者ID:buckket,項目名稱:twtxt,代碼行數:13,代碼來源:helper.py

示例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?') 
開發者ID:veripress,項目名稱:veripress,代碼行數:32,代碼來源:theme.py

示例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 
開發者ID:redcanari,項目名稱:canari3,代碼行數:11,代碼來源:framework.py

示例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')) 
開發者ID:Netflix,項目名稱:metaflow,代碼行數:12,代碼來源:main_cli.py

示例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()) 
開發者ID:chaostoolkit,項目名稱:chaostoolkit,代碼行數:44,代碼來源:cli.py

示例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),
            )
        ) 
開發者ID:timofurrer,項目名稱:w1thermsensor,代碼行數:49,代碼來源:cli.py


注:本文中的click.BadArgumentUsage方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。