Python argparse._AppendAction() Examples

The following are 9 code examples of argparse._AppendAction(). 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 argparse , or try the search function .
Example #1
Source File: test_cli.py    From mutatest with MIT License 6 votes vote down vote up
def test_get_parser_actions(mock_parser):
    """Parser action types based on basic inputs."""
    expected_actions = {
        "-h": "--help",
        "-e": "--exclude",
        "-b": "--blacklist",
        "--debug": "--debug",
    }
    expected_types = {
        argparse._HelpAction: ["help"],
        argparse._AppendAction: ["exclude"],
        argparse._StoreAction: ["blacklist"],
        argparse._StoreTrueAction: ["debug"],
    }

    parser_actions = cli.get_parser_actions(mock_parser)
    assert parser_actions.actions == expected_actions
    assert parser_actions.action_types == expected_types 
Example #2
Source File: argparse_completer.py    From WebPocket with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,
                 option_strings,
                 dest,
                 nargs=None,
                 const=None,
                 default=None,
                 type=None,
                 choices=None,
                 required=False,
                 help=None,
                 metavar=None) -> None:

        _RangeAction.__init__(self, nargs)

        argparse._AppendAction.__init__(self,
                                        option_strings=option_strings,
                                        dest=dest,
                                        nargs=self.nargs_adjusted,
                                        const=const,
                                        default=default,
                                        type=type,
                                        choices=choices,
                                        required=required,
                                        help=help,
                                        metavar=metavar) 
Example #3
Source File: triagers.py    From ansibullbot with GNU General Public License v3.0 5 votes vote down vote up
def add_dynamic_attr(cls, klass):
    parser = klass.create_parser()
    import argparse
    for action in parser._actions:
        if isinstance(action, argparse._HelpAction):
            continue

        if isinstance(action, (argparse._StoreTrueAction, argparse._StoreTrueAction)):
            cls.locals[action.dest] = [bool]
        elif isinstance(action, argparse._CountAction):
            cls.locals[action.dest] = [int]
        elif isinstance(action, (argparse._AppendAction, argparse._AppendConstAction)):
            cls.locals[action.dest] = [list]
        else:
            cls.locals[action.dest] = [action.type] 
Example #4
Source File: configargparse.py    From zoe with Apache License 2.0 5 votes vote down vote up
def convert_item_to_command_line_arg(self, action, key, value):
        """Converts a config file or env var key + value to a list of
        commandline args to append to the commandline.

        Args:
            action: The argparse Action object for this setting, or None if this
                config file setting doesn't correspond to any defined
                configargparse arg.
            key: string (config file key or env var name)
            value: parsed value of type string or list
        """
        args = []
        if action is None:
            command_line_key = \
                self.get_command_line_key_for_unknown_config_file_setting(key)
        else:
            command_line_key = action.option_strings[-1]

        # handle boolean value
        if action is not None and type(action) in ACTION_TYPES_THAT_DONT_NEED_A_VALUE:
            if value.lower() in ("true", "false", "yes", "no"):
                args.append(command_line_key)
            else:
                self.error("Unexpected value for %s: '%s'. Expecting 'true', "
                           "'false', 'yes', or 'no'" % (key, value))
        elif type(value) == list:
            if action is not None and type(action) != argparse._AppendAction:
                self.error(("%s can't be set to a list '%s' unless its "
                            "action type is changed to 'append'") % (key, value))
            for list_elem in value:
                args.append(command_line_key)
                args.append(str(list_elem))
        elif type(value) == str:
            args.append(command_line_key)
            args.append(value)
        else:
            raise ValueError("Unexpected value type %s for value: %s" % (
                type(value), value))

        return args 
Example #5
Source File: cli.py    From mutatest with MIT License 4 votes vote down vote up
def get_parser_actions(parser: argparse.ArgumentParser) -> ParserActionMap:
    """Create a parser action map used when creating the command list mixed from the
    CLI and the ini config file.

    ParserActionMap has both actions and types e.g.,

    .. code-block:: python

        # action-types:

        {argparse._HelpAction: ['help'],
         mutatest.cli.ValidCategoryAction: ['blacklist', 'whitelist'],
         argparse._AppendAction: ['exclude'],
         argparse._StoreAction: ['mode', 'output', 'src', 'testcmds'],
         mutatest.cli.PositiveIntegerAction: ['nlocations', 'rseed', 'exception'],
         argparse._StoreTrueAction: ['debug', 'nocov']}

        # actions:

        {'-h': '--help',
         '-b': '--blacklist',
         '-e': '--exclude',
         '-m': '--mode',
         '-n': '--nlocations',
         '-o': '--output',
         '-r': '--rseed',
         '-s': '--src',
         '-t': '--testcmds',
         '-w': '--whitelist',
         '-x': '--exception',
         '--debug': '--debug',
         '--parallel': '--parallel',
         '--nocov': '--nocov'}

    Args:
        parser: the argparser

    Returns:
        ParserActionMap: includes actions and action_types
    """
    actions: Dict[str, str] = {}
    action_types: Dict[Any, List[str]] = {}

    for action in parser._actions:
        # build the actions
        # option_strings is either [-r, --rseed] or [--debug] for short-hand options
        actions[action.option_strings[0]] = action.option_strings[-1]

        # build the action_types
        # values align to the keywords that can be used in the INI config
        try:
            action_types[type(action)].append(action.option_strings[-1].strip("--"))

        except KeyError:
            action_types[type(action)] = [action.option_strings[-1].strip("--")]

    return ParserActionMap(actions=actions, action_types=action_types) 
Example #6
Source File: cli.py    From mutatest with MIT License 4 votes vote down vote up
def parse_ini_config_with_cli(
    parser: argparse.ArgumentParser, ini_config: configparser.SectionProxy, cli_args: Sequence[str]
) -> List[str]:
    """Combine the INI file settings with the CLI args, using the CLI args as the override.

    Args:
        parser: the argparser
        ini_config: the section of the parsed INI file
        cli_args: the original cli args

    Returns:
        Updated args mixing INI and CLI, with CLI used as the override
    """

    action_maps = get_parser_actions(parser)
    final_args_list = [action_maps.actions.get(i, i) for i in cli_args]

    def ws_proc(value: str) -> List[str]:
        """Convenience function for stripping newlines from configparser section values
        and splitting whitespace to a list.
        """
        return value.replace("\n", " ").split()

    for k in ini_config.keys():
        arg_key = f"--{k}"

        if arg_key in action_maps.actions.values() and arg_key not in final_args_list:

            if k in action_maps.action_types[mutatest.cli.ValidCategoryAction]:
                values = ws_proc(ini_config[k])
                final_args_list.extend([arg_key] + values)

            elif k in action_maps.action_types[argparse._StoreTrueAction]:
                if ini_config.getboolean(k):
                    final_args_list.append(arg_key)

            elif k in action_maps.action_types[argparse._AppendAction]:
                values = ws_proc(ini_config[k])
                final_args_list.extend(
                    [i for j in list(itertools.product([arg_key], values)) for i in j]
                )

            else:
                final_args_list.extend([arg_key, ini_config[k]])

    return final_args_list


####################################################################################################
# CLI REPORTING OUTPUTS
#################################################################################################### 
Example #7
Source File: show.py    From openaps with MIT License 4 votes vote down vote up
def format_cli (self, report):
    usage = self.app.devices[report.fields.get('device')]
    task = self.app.actions.commands['add'].usages.commands[usage.name].method.commands[report.fields['use']]

    line = [ 'openaps', 'use', usage.name, report.fields.get('use') ]
    params = [ ]
    config = task.method.from_ini(dict(**report.fields))

    for act in task.method.parser._actions:
      def accrue (switch):
        if switch.startswith('-'):
          params.insert(0, switch)
        else:
          params.append(switch)

      # if act.dest in report.fields:
      if act.dest in config:
        if act.option_strings:

          if report.fields.get(act.dest):
            if type(act) in [argparse._StoreTrueAction, argparse._StoreFalseAction ]:
              expected = act.const
              expected = act.default
              found = config.get(act.dest)
              if type(act) is argparse._StoreFalseAction:
                expected = True
                found = found

              if expected != found:
                accrue(act.option_strings[0])
            elif type(act) in [argparse._StoreConstAction, ]:
              expected = act.default
              found = config.get(act.dest)
              if expected != found:
                accrue(act.option_strings[0])
            elif type(act) in [argparse._AppendAction, ]:
              if config.get(act.dest) != act.default:
                for item in config.get(act.dest):
                  accrue(act.option_strings[0] + ' ' + item + '')
              pass
            elif type(act) in [argparse._StoreAction, ]:
              if config.get(act.dest) != act.default:
                accrue(act.option_strings[0] + ' "' + report.fields.get(act.dest) + '"')
            else:
              accrue(act.option_strings[0] + ' "' + report.fields.get(act.dest) + '"')
        else:
          accrue(report.fields.get(act.dest))


    return ' '.join(line + params) 
Example #8
Source File: configargparse.py    From pipelines with MIT License 4 votes vote down vote up
def convert_item_to_command_line_arg(self, action, key, value):
        """Converts a config file or env var key + value to a list of
        commandline args to append to the commandline.

        Args:
            action: The argparse Action object for this setting, or None if this
                config file setting doesn't correspond to any defined
                configargparse arg.
            key: string (config file key or env var name)
            value: parsed value of type string or list
        """
        args = []
        if action is None:
            command_line_key = \
                self.get_command_line_key_for_unknown_config_file_setting(key)
        else:
            command_line_key = action.option_strings[-1]

        # handle boolean value
        if action is not None and isinstance(action, ACTION_TYPES_THAT_DONT_NEED_A_VALUE):
            if value.lower() in ("true", "yes"):
                args.append( command_line_key )
            elif value.lower() in ("false", "no"):
                # don't append when set to "false" / "no"
                pass
            else:
                self.error("Unexpected value for %s: '%s'. Expecting 'true', "
                           "'false', 'yes', or 'no'" % (key, value))
        elif isinstance(value, list):
            if action is None or isinstance(action, argparse._AppendAction):
                for list_elem in value:
                    args.append( command_line_key )
                    args.append( str(list_elem) )
            elif (isinstance(action, argparse._StoreAction) and action.nargs in ('+', '*')) or (
                isinstance(action.nargs, int) and action.nargs > 1):
                args.append( command_line_key )
                for list_elem in value:
                    args.append( str(list_elem) )
            else:
                self.error(("%s can't be set to a list '%s' unless its action type is changed "
                            "to 'append' or nargs is set to '*', '+', or > 1") % (key, value))
        elif isinstance(value, str):
            args.append( command_line_key )
            args.append( value )
        else:
            raise ValueError("Unexpected value type %s for value: %s" % (
                type(value), value))

        return args 
Example #9
Source File: configargparse.py    From ConfigArgParse with MIT License 4 votes vote down vote up
def convert_item_to_command_line_arg(self, action, key, value):
        """Converts a config file or env var key + value to a list of
        commandline args to append to the commandline.

        Args:
            action: The argparse Action object for this setting, or None if this
                config file setting doesn't correspond to any defined
                configargparse arg.
            key: string (config file key or env var name)
            value: parsed value of type string or list
        """
        args = []

        if action is None:
            command_line_key = \
                self.get_command_line_key_for_unknown_config_file_setting(key)
        else:
            command_line_key = action.option_strings[-1]

        # handle boolean value
        if action is not None and isinstance(action, ACTION_TYPES_THAT_DONT_NEED_A_VALUE):
            if value.lower() in ("true", "yes", "1"):
                args.append( command_line_key )
            elif value.lower() in ("false", "no", "0"):
                # don't append when set to "false" / "no"
                pass
            else:
                self.error("Unexpected value for %s: '%s'. Expecting 'true', "
                           "'false', 'yes', 'no', '1' or '0'" % (key, value))
        elif isinstance(value, list):
            accepts_list_and_has_nargs = action is not None and action.nargs is not None and (
                   isinstance(action, argparse._StoreAction) or isinstance(action, argparse._AppendAction)
            ) and (
                action.nargs in ('+', '*') or (isinstance(action.nargs, int) and action.nargs > 1)
            )

            if action is None or isinstance(action, argparse._AppendAction):
                for list_elem in value:
                    if accepts_list_and_has_nargs and isinstance(list_elem, list):
                        args.append(command_line_key)
                        for sub_elem in list_elem:
                            args.append(str(sub_elem))
                    else:
                        args.append( "%s=%s" % (command_line_key, str(list_elem)) )
            elif accepts_list_and_has_nargs:
                args.append( command_line_key )
                for list_elem in value:
                    args.append( str(list_elem) )
            else:
                self.error(("%s can't be set to a list '%s' unless its action type is changed "
                            "to 'append' or nargs is set to '*', '+', or > 1") % (key, value))
        elif isinstance(value, str):
            args.append( "%s=%s" % (command_line_key, value) )
        else:
            raise ValueError("Unexpected value type {} for value: {}".format(
                type(value), value))

        return args