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


Python click.Choice方法代碼示例

本文整理匯總了Python中click.Choice方法的典型用法代碼示例。如果您正苦於以下問題:Python click.Choice方法的具體用法?Python click.Choice怎麽用?Python click.Choice使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在click的用法示例。


在下文中一共展示了click.Choice方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: ask_for_import

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def ask_for_import(project: Project) -> None:
    """Show possible importable files and ask user to decide"""
    importable_files = list(find_importable_files(project))
    if not importable_files:
        return
    stream.echo(
        stream.cyan("Found following files from other formats that you may import:")
    )
    for i, (key, filepath) in enumerate(importable_files):
        stream.echo(f"{i}. {stream.green(filepath.as_posix())} ({key})")
    stream.echo(
        "{}. {}".format(
            len(importable_files),
            stream.yellow("don't do anything, I will import later."),
        )
    )
    choice = click.prompt(
        "Please select:",
        type=click.Choice([str(i) for i in range(len(importable_files) + 1)]),
        show_default=False,
    )
    if int(choice) == len(importable_files):
        return
    key, filepath = importable_files[int(choice)]
    do_import(project, filepath, key) 
開發者ID:frostming,項目名稱:pdm,代碼行數:27,代碼來源:actions.py

示例2: terminal

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def terminal(port):
    click.echo(click.style('NOTE: This is an early prototype of the terminal.'
                           ' Nothing is guaranteed to work.', bold=True))
    if port == 'default':
        if len(prosflasher.ports.list_com_ports()) == 1:
            port = prosflasher.ports.list_com_ports()[0].device
        elif len(prosflasher.ports.list_com_ports()) > 1:
            click.echo('Multiple ports were found:')
            click.echo(prosflasher.ports.create_port_list())
            port = click.prompt('Select a port to open',
                                type=click.Choice([p.device for p in prosflasher.ports.list_com_ports()]))
        else:
            click.echo('No ports were found.')
            click.get_current_context().abort()
            sys.exit()
    ser = prosflasher.ports.create_serial(port, serial.PARITY_NONE)
    term = proscli.serial_terminal.Terminal(ser)
    signal.signal(signal.SIGINT, term.stop)
    term.start()
    while term.alive:
        time.sleep(0.005)
    term.join()
    ser.close()
    print('Exited successfully')
    sys.exit(0) 
開發者ID:purduesigbots,項目名稱:pros-cli2,代碼行數:27,代碼來源:terminal.py

示例3: pagination_options

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def pagination_options(sort_fields, default_sort):
    """Shared pagination options."""

    def _pagination_options(f):
        f = click.option('--limit', metavar='LIMIT', type=click.INT,
                         help='Maximum number of items to show.')(f)
        f = click.option('--page', metavar='PAGE', type=click.INT,
                         help='Page to retrieve items from. This is '
                         'influenced by the size of LIMIT.')(f)
        f = click.option('--sort', metavar='FIELD', default=default_sort,
                         type=click.Choice(sort_fields),
                         help='Sort output on given field.')(f)

        return f

    return _pagination_options 
開發者ID:getpatchwork,項目名稱:git-pw,代碼行數:18,代碼來源:utils.py

示例4: format_options

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def format_options(original_function=None, headers=None):
    """Shared output format options."""

    def _format_options(f):
        f = click.option('--format', '-f', 'fmt', default=None,
                         type=click.Choice(['simple', 'table', 'csv']),
                         help="Output format. Defaults to the value of "
                         "'git config pw.format' else 'table'.")(f)

        if headers:
            f = click.option('--column', '-c', 'headers', metavar='COLUMN',
                             multiple=True, default=headers,
                             type=click.Choice(headers),
                             help='Columns to be included in output.')(f)
        return f

    if original_function:
        return _format_options(original_function)

    return _format_options 
開發者ID:getpatchwork,項目名稱:git-pw,代碼行數:22,代碼來源:utils.py

示例5: _handle_github

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def _handle_github(self):
        """Handle exception and submit it as GitHub issue."""
        value = click.prompt(
            _BUG + click.style(
                '1. Open an issue by typing "open";\n',
                fg='green',
            ) + click.style(
                '2. Print human-readable information by typing '
                '"print";\n',
                fg='yellow',
            ) + click.style(
                '3. See the full traceback without submitting details '
                '(default: "ignore").\n\n',
                fg='red',
            ) + 'Please select an action by typing its name',
            type=click.Choice([
                'open',
                'print',
                'ignore',
            ], ),
            default='ignore',
        )
        getattr(self, '_process_' + value)() 
開發者ID:SwissDataScienceCenter,項目名稱:renku-python,代碼行數:25,代碼來源:exception_handler.py

示例6: codegen_options

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def codegen_options(f):
    f = click.option(
        "-c", "--categories", multiple=True, default=default_categories,
        type=click.Choice(all_categories),
        help="A list of the categories of inputs and outputs that should "
        "be enabled"
    )(f)
    f = click.option(
        "-f", "--param_file",
        type=click.File(),
        help="""YAML or JSON file describing the firmware module configuration to be flashed.
        This is the same file that is used for rosparam in the launch file."""
        "code"
    )(f)
    f = click.option(
        "-p", "--plugin", multiple=True, help="Enable a specific plugin"
    )(f)
    f = click.option(
        "-t", "--target", help="PlatformIO target (e.g.  upload)"
    )(f)
    f = click.option(
        "--status_update_interval", default=5,
        help="Minimum interval between driver status updates (in seconds)"
    )(f)
    return f 
開發者ID:OpenAgricultureFoundation,項目名稱:openag_python,代碼行數:27,代碼來源:__init__.py

示例7: json_schema_to_click_type

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def json_schema_to_click_type(schema: dict) -> tuple:
    """
    A generic handler of a single property JSON schema to :class:`click.ParamType` converter

    :param schema: JSON schema property to operate on
    :return: Tuple of :class:`click.ParamType`, `description`` of option and optionally a :class:`click.Choice`
     if the allowed values are a closed list (JSON schema ``enum``)
    """
    choices = None
    if isinstance(schema["type"], list):
        if "string" in schema["type"]:
            schema["type"] = "string"
    click_type = SCHEMA_BASE_MAP[schema["type"]]
    description = schema.get("title")
    if schema.get("enum"):
        # todo handle multi type enums better (or at all)
        enum = [value for value in schema["enum"] if isinstance(value, str)]
        choices = click.Choice(enum)
    return click_type, description, choices 
開發者ID:liiight,項目名稱:notifiers,代碼行數:21,代碼來源:dynamic_click.py

示例8: exec_command

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def exec_command(command, service, replica, interactive):
    """Exec management commands"""
    if not replica:
        details = get_details(service)
        if not details:
            click.echo('Service {} does not exist!'.format(service), err=True)
            return
        pods = details['pods']
        # TODO: just find the available pods
        if len(pods) == 1:
            replica = pods[0]['name']
        else:
            pod_names = [pod['name'] for pod in pods]
            for pod_name in pod_names:
                click.echo('- {}'.format(pod_name))

            replica = click.prompt('Please choose one of the replicas above', type=click.Choice(pod_names))
    if interactive:
        click.echo('Initializing session...')
        response = post_session(replica, command)
        click.echo('Connecting to the replica...')
        start_session(response['session_key'])
    else:
        response = post_exec(replica, command)
        click.echo(response['message']) 
開發者ID:fandoghpaas,項目名稱:fandogh-cli,代碼行數:27,代碼來源:exec_commands.py

示例9: card_filtering_command

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def card_filtering_command(f):
    '''Add common options to a click function that will filter Trello cards'''
    f = click.option('-t', '--tags', default=None, help='Filter cards by this comma-separated list of tag names')(f)
    f = click.option('--no-tags', is_flag=True, default=None, help='Only show cards which have no tags')(f)
    f = click.option('-m', '--match', help='Filter cards to this regex on their title', default=None)(f)
    f = click.option('-l', '--listname', help='Only show cards from this list', default=None)(f)
    f = click.option('--attachments', is_flag=True, help='Only show cards which have attachments', default=None)(f)
    f = click.option('--has-due', is_flag=True, help='Only show cards which have due dates', default=None)(f)
    f = click.option(
        '-s',
        '--status',
        default='visible',
        help='Show cards in this state',
        type=click.Choice(['all', 'closed', 'open', 'visible']),
    )(f)
    return f 
開發者ID:delucks,項目名稱:gtd.py,代碼行數:18,代碼來源:gtd.py

示例10: options

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def options(cls, how=None):
        """ Prepare command line options """
        return [
            click.option(
                '-p', '--package', metavar='PACKAGE', multiple=True,
                help='Package name or path to rpm to be installed.'),
            click.option(
                '-D', '--directory', metavar='PATH', multiple=True,
                help='Path to a local directory with rpm packages.'),
            click.option(
                '-c', '--copr', metavar='REPO', multiple=True,
                help='Copr repository to be enabled.'),
            click.option(
                '-m', '--missing', metavar='ACTION',
                type=click.Choice(['fail', 'skip']),
                help='Action on missing packages, fail (default) or skip.'),
            ] + super().options(how) 
開發者ID:psss,項目名稱:tmt,代碼行數:19,代碼來源:install.py

示例11: run_profile

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def run_profile(profile_name, tag_name):
    registry = config.get_env(profile_name, 'docker_registry')
    vol_mapping = config.get_env(profile_name, 'vol_mapping')
    port_mapping = config.get_env(profile_name, 'port_mapping')
    env_vars = config.get_env(profile_name, 'env_vars')
    
    command = "docker run -d "
    command += '--name ' + profile_name
    command += ' -p ' + port_mapping
    command += ' -v ' + vol_mapping
    command += ' -e ' + env_vars
    tag = 'latest'
    if tag_name == '':
        logger.log_bl('\nGetting top 5 available tags of ' + profile_name + ' from Amazon ECR registry...')
        tag_list = utils.cmd_exec("aws ecr describe-images --repository-name " + profile_name + " --output text --query 'sort_by(imageDetails,& imagePushedAt)[*].imageTags[*]' | tr '\t' '\n' | tail -5")
        tag_list = list(reversed(tag_list.split('\n')))
        tag = click.prompt(logger.style('\nSelect an tag to deploy: ?'), type=click.Choice(tag_list))
    logger.log_g('\nYou have selected tag: [ ' + tag + ' ]  for your application')
    command += ' ' + registry + '/' + profile_name + ':' + tag
    logger.debug('final command : ' + command)
    logger.log_y('\nKilling old container if exist')
    utils.cmd_exec('docker rm -f ' + profile_name)
    utils.cmd_exec(command)
    logger.log_g("\nSuccessfully started " + profile_name + " application . Please check logs using: ")
    logger.log_cy("\n                 docker logs -f " + profile_name + "                          \n") 
開發者ID:javatechy,項目名稱:dokr,代碼行數:27,代碼來源:docker_helper.py

示例12: docker_storage_driver_option

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def docker_storage_driver_option(command: Callable[..., None],
                                 ) -> Callable[..., None]:
    """
    Option for choosing the Docker storage driver to use inside the container.
    """
    function = click.option(
        '--docker-storage-driver',
        type=click.Choice(sorted(DOCKER_STORAGE_DRIVERS.keys())),
        default='auto',
        show_default=True,
        help=(
            'The storage driver to use for Docker in Docker. '
            "By default this uses the host's driver."
        ),
        callback=_get_docker_storage_driver,
    )(command)  # type: Callable[..., None]
    return function 
開發者ID:dcos,項目名稱:dcos-e2e,代碼行數:19,代碼來源:_docker_storage_driver.py

示例13: docker_version_option

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def docker_version_option(command: Callable[..., None],
                          ) -> Callable[..., None]:
    """
    Option for choosing the Docker version to use inside the container.
    """
    function = click.option(
        '--docker-version',
        type=click.Choice(sorted(_DOCKER_VERSIONS.keys())),
        default='18.06.3-ce',
        envvar='MINIDCOS_NODE_DOCKER_VERSION',
        show_default=True,
        help=(
            'The Docker version to install on the nodes. '
            'This can be provided by setting the '
            '`MINIDCOS_NODE_DOCKER_VERSION` environment variable.'
        ),
        callback=_get_docker_version,
    )(command)  # type: Callable[..., None]
    return function 
開發者ID:dcos,項目名稱:dcos-e2e,代碼行數:21,代碼來源:_docker_version.py

示例14: variant_option

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def variant_option(command: Callable[..., None]) -> Callable[..., None]:
    """
    An option decorator for a DC/OS variant.
    """
    function = click.option(
        '--variant',
        type=click.Choice(['auto', 'oss', 'enterprise']),
        default='auto',
        help=(
            'Choose the DC/OS variant. '
            'If the variant does not match the variant of the given '
            'installer, an error will occur. '
            'Using "auto" finds the variant from the installer. '
            'Finding the variant from the installer takes some time and so '
            'using another option is a performance optimization.'
        ),
    )(command)  # type: Callable[..., None]
    return function 
開發者ID:dcos,項目名稱:dcos-e2e,代碼行數:20,代碼來源:__init__.py

示例15: _maybe_apply_flag

# 需要導入模塊: import click [as 別名]
# 或者: from click import Choice [as 別名]
def _maybe_apply_flag(param, flags):
    arg_name = _param_arg_name(param)
    if not arg_name or not isinstance(param, click.Option):
        log.debug("skipping %s - not a flag option", param.name)
        return
    flag_name = param.name
    flags[flag_name] = attrs = {}
    if arg_name != flag_name:
        attrs["arg-name"] = arg_name
    if param.help:
        attrs["description"] = param.help
    if param.default is not None:
        attrs["default"] = _ensure_json_encodable(param.default, flag_name)
    if isinstance(param.type, click.Choice):
        attrs["choices"] = _ensure_json_encodable(param.type.choices, flag_name)
    if param.required:
        attrs["required"] = True
    if param.is_flag:
        attrs["arg-switch"] = param.default
    log.debug("added flag %r: %r", flag_name, attrs) 
開發者ID:guildai,項目名稱:guildai,代碼行數:22,代碼來源:click_flags.py


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