Python click.Choice() Examples

The following are 30 code examples of click.Choice(). 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: terminal.py    From pros-cli2 with Mozilla Public License 2.0 7 votes vote down vote up
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) 
Example #2
Source File: gtd.py    From gtd.py with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #3
Source File: actions.py    From pdm with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: utils.py    From git-pw with MIT License 6 votes vote down vote up
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 
Example #5
Source File: decorators.py    From ceph-lcm with Apache License 2.0 6 votes vote down vote up
def with_color(func):
    """Decorator which adds --color option if available."""

    if pygments is None:
        def decorator(*args, **kwargs):
            kwargs["color"] = None
            return func(*args, **kwargs)
    else:
        decorator = click.option(
            "--color",
            default=None,
            type=click.Choice(["light", "dark"]),
            help=(
                "Colorize output. By default no color is used. "
                "Parameter means colorscheme of the terminal")
        )(func)

    decorator = six.wraps(func)(decorator)

    return decorator 
Example #6
Source File: utils.py    From git-pw with MIT License 6 votes vote down vote up
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 
Example #7
Source File: json_schema.py    From diffy with Apache License 2.0 6 votes vote down vote up
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"):
        choices = click.Choice(schema["enum"])
    return click_type, description, choices 
Example #8
Source File: exception_handler.py    From renku-python with Apache License 2.0 6 votes vote down vote up
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)() 
Example #9
Source File: __init__.py    From openag_python with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #10
Source File: dynamic_click.py    From notifiers with MIT License 6 votes vote down vote up
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 
Example #11
Source File: __init__.py    From dcos-e2e with Apache License 2.0 6 votes vote down vote up
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 
Example #12
Source File: _docker_version.py    From dcos-e2e with Apache License 2.0 6 votes vote down vote up
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 
Example #13
Source File: exec_commands.py    From fandogh-cli with MIT License 6 votes vote down vote up
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']) 
Example #14
Source File: _docker_storage_driver.py    From dcos-e2e with Apache License 2.0 6 votes vote down vote up
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 
Example #15
Source File: docker_helper.py    From dokr with MIT License 6 votes vote down vote up
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") 
Example #16
Source File: install.py    From tmt with MIT License 6 votes vote down vote up
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) 
Example #17
Source File: __main__.py    From releasetool with Apache License 2.0 5 votes vote down vote up
def _language_option():
    return click.option(
        "--language",
        prompt=f"Which language ({', '.join(_language_choices)})?",
        type=click.Choice(_language_choices),
        default=_detect_language,
        cls=_OptionPromptIfNone,
    ) 
Example #18
Source File: params.py    From gandi.cli with GNU General Public License v3.0 5 votes vote down vote up
def convert(self, value, param, ctx):
        """ Internal method to use correct context. """
        self.gandi = ctx.obj
        return click.Choice.convert(self, value, param, ctx) 
Example #19
Source File: params.py    From gandi.cli with GNU General Public License v3.0 5 votes vote down vote up
def convert(self, value, param, ctx):
        """ Convert value to int. """
        self.gandi = ctx.obj
        value = click.Choice.convert(self, value, param, ctx)
        return int(value) 
Example #20
Source File: params.py    From gandi.cli with GNU General Public License v3.0 5 votes vote down vote up
def convert(self, value, param, ctx):
        """ Convert value to int. """
        self.gandi = ctx.obj
        value = click.Choice.convert(self, value, param, ctx)
        return int(value) 
Example #21
Source File: validate.py    From core with Apache License 2.0 5 votes vote down vote up
def validate_page(page, **kwargs):
    '''
    Validate PAGE against OCR-D conventions
    '''
    _inform_of_result(PageValidator.validate(filename=page, **kwargs))

#  @validate_cli.command('zip')
#  @click.argument('src', type=click.Path(dir_okay=True, readable=True, resolve_path=True), required=True)
#  @click.option('-Z', '--skip-unzip', help="Treat SRC as a directory not a ZIP", is_flag=True, default=False)
#  @click.option('-B', '--skip-bag', help="Whether to skip all checks of manifests and files", is_flag=True, default=False)
#  @click.option('-C', '--skip-checksums', help="Whether to omit checksum checks but still check basic BagIt conformance", is_flag=True, default=False)
#  @click.option('-D', '--skip-delete', help="Whether to skip deleting the unpacked OCRD-ZIP dir after valdiation", is_flag=True, default=False)
#  @click.option('-j', '--processes', help="Number of parallel processes", type=int, default=1)
#  def validate(src, **kwargs):
#      """
#      Validate OCRD-ZIP

#      SRC must exist an be an OCRD-ZIP, either a ZIP file or a directory.
#      """
#      _inform_of_result(OcrdZipValidator(Resolver(), src).validate(**kwargs))

#  @validate_cli.command('workspace')
#  @click.option('-a', '--download', is_flag=True, help="Download all files")
#  @click.option('-s', '--skip', help="Tests to skip", default=[], multiple=True, type=click.Choice(['imagefilename', 'dimension', 'mets_unique_identifier', 'mets_file_group_names', 'mets_files', 'pixel_density', 'page', 'url']))
#  @click.option('--page-textequiv-consistency', '--page-strictness', help="How strict to check PAGE multi-level textequiv consistency", type=click.Choice(['strict', 'lax', 'fix', 'off']), default='strict')
#  @click.option('--page-coordinate-consistency', help="How fierce to check PAGE multi-level coordinate consistency", type=click.Choice(['poly', 'baseline', 'both', 'off']), default='poly')
#  @click.argument('mets_url')
#  def validate_workspace(mets_url, **kwargs):
#      '''
#          Validate a workspace
#      '''
#      _inform_of_result(WorkspaceValidator.validate(Resolver(), mets_url, **kwargs)) 
Example #22
Source File: params.py    From gandi.cli with GNU General Public License v3.0 5 votes vote down vote up
def convert(self, value, param, ctx):
        """ Convert value to uppercase. """
        self.gandi = ctx.obj
        value = value.upper()
        return click.Choice.convert(self, value, param, ctx) 
Example #23
Source File: interactive.py    From tutor with GNU Affero General Public License v3.0 5 votes vote down vote up
def ask_choice(question, key, config, defaults, choices):
    default = config.get(key, defaults[key])
    answer = click.prompt(
        fmt.question(question),
        type=click.Choice(choices),
        prompt_suffix=" ",
        default=default,
        show_choices=False,
    )
    config[key] = answer 
Example #24
Source File: benchmark.py    From devito with MIT License 5 votes vote down vote up
def option_simulation(f):
    def default_list(ctx, param, value):
        return list(value if len(value) > 0 else (2, ))

    options = [
        click.option('-P', '--problem', help='Problem name',
                     type=click.Choice(['acoustic', 'tti',
                                        'elastic', 'acoustic_ssa', 'viscoelastic'])),
        click.option('-d', '--shape', default=(50, 50, 50),
                     help='Number of grid points along each axis'),
        click.option('-s', '--spacing', default=(20., 20., 20.),
                     help='Spacing between grid sizes in meters'),
        click.option('-n', '--nbl', default=10,
                     help='Number of boundary layers'),
        click.option('-so', '--space-order', type=int, multiple=True,
                     callback=default_list, help='Space order of the simulation'),
        click.option('-to', '--time-order', type=int, multiple=True,
                     callback=default_list, help='Time order of the simulation'),
        click.option('-t', '--tn', default=250,
                     help='End time of the simulation in ms'),
        click.option('-op', '--operator', default='forward', help='Operator to run',
                     type=click.Choice(['forward', 'adjoint',
                                        'jacobian', 'jacobian_adjoint']))]
    for option in reversed(options):
        f = option(f)
    return f 
Example #25
Source File: __main__.py    From ocdeployer with MIT License 5 votes vote down vote up
def output_option(func):
    """Click decorator used for output option, shared by several commands."""
    option = click.option(
        "--output",
        "-o",
        default=None,
        type=click.Choice(["yaml", "json"]),
        help="Output data using yaml or json format",
    )
    return option(func) 
Example #26
Source File: click_cwl_translation.py    From argparse2tool with Apache License 2.0 5 votes vote down vote up
def __cwl_param_from_type(self, param):
        """Based on a type, convert to appropriate cwlt class
        """
        if param.default == sys.stdout:
            param.default = None
        if hasattr(param, 'optional'):
            optional = param.optional
        else:
            optional = False
        if not hasattr(param, 'items_type'):
            param.items_type = None
        prefix = None
        position = None
        if param.param_type_name == 'option':
            prefix = param.opts[-1]
        if not param.required:
            optional = True
        else:
            self.positional_count += 1
            position = self.positional_count
        param_type = self.get_cwl_type(param.type) or 'str'
        kwargs_positional = {'id': param.name,
                             'position': position,
                             'description': getattr(param, 'help', param.human_readable_name),
                             'default': param.default,
                             'prefix': prefix,
                             'optional': optional,
                             'items_type': param.items_type,
                             'type': param_type}

        if type(param.type) is click.Choice:
            kwargs_positional['choices'] = param.type.choices
        if (isinstance(param.type, click.types.File) and 'w' in param.type.mode) \
                or (self.generate_outputs and 'output' in param.dest):
            cwlparam = cwlt.OutputParam(**kwargs_positional)
        else:
            cwlparam = cwlt.Param(**kwargs_positional)
        return cwlparam 
Example #27
Source File: util.py    From q2cli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_primitive(ast):
    import click

    mapping = {
        'Int': int,
        'Str': str,
        'Float': float,
        'Color': str,
        'Bool': bool
    }
    # TODO: it would be a good idea to refactor this someday, but until then
    # just handle the few predicates we know about.
    predicate = ast['predicate']
    if predicate:
        if predicate['name'] == 'Choices' and ast['name'] == 'Str':
            return click.Choice(predicate['choices'])
        elif predicate['name'] == 'Range' and ast['name'] == 'Int':
            start = predicate['range'][0]
            end = predicate['range'][1]
            # click.IntRange is always inclusive
            if start is not None and not predicate['inclusive'][0]:
                start += 1
            if end is not None and not predicate['inclusive'][1]:
                end -= 1
            return click.IntRange(start, end)
        elif predicate['name'] == 'Range' and ast['name'] == 'Float':
            # click.FloatRange will be in click 7.0, so for now the
            # range handling will just fallback to qiime2.
            return mapping['Float']
        else:
            raise NotImplementedError()
    else:
        return mapping[ast['name']] 
Example #28
Source File: test_click2cwl.py    From argparse2tool with Apache License 2.0 5 votes vote down vote up
def test_choices(self):
        choices = ['rock', 'scissors', 'paper']

        @click.command()
        @click.option('--item', type=click.Choice(choices))
        def function(item):
            pass

        parser_name = 'test-choices.py'
        tool = self.generate_and_open_test_tool(self.standard_testargs(parser_name), function, parser_name)
        self.assertEqual(tool.inputs['item'].type[1]['symbols'], choices) 
Example #29
Source File: test_click2cwl.py    From argparse2tool with Apache License 2.0 5 votes vote down vote up
def prepare_argument_parser():
        @click.command()
        @click.argument('keyword', type=click.STRING)
        @click.option('--choices', type=click.Choice(['md5', 'sha1']))
        @click.option('--double-type', type=(str, int), default=(None, None))
        def function():
            pass

        return function 
Example #30
Source File: _options.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def node_transport_option(command: Callable[..., None]) -> Callable[..., None]:
    """
    An option decorator for node transport options.
    """
    transports = {
        'ssh': Transport.SSH,
        'docker-exec': Transport.DOCKER_EXEC,
    }

    backend_default = Docker().transport
    [default_option] = [
        transport for transport in transports
        if transports[transport] == backend_default
    ]

    function = click.option(
        '--transport',
        type=click.Choice(sorted(transports.keys())),
        callback=lambda ctx, param, value: transports[value],
        default=default_option,
        show_default=True,
        envvar='MINIDCOS_DOCKER_TRANSPORT',
        help=(
            'The communication transport to use. '
            'On macOS the SSH transport requires IP routing to be set up. '
            'See "minidcos docker setup-mac-network". '
            'It also requires the "ssh" command to be available. '
            'This can be provided by setting the `MINIDCOS_DOCKER_TRANSPORT` '
            'environment variable. '
            'When using a TTY, different transports may use different line '
            'endings.'
        ),
    )(command)  # type: Callable[..., None]
    return function