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


Python argparse._StoreAction方法代碼示例

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


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

示例1: test_get_parser_actions

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
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 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:20,代碼來源:test_cli.py

示例2: generate_base_doc

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
def generate_base_doc(app, hamm_help):
    myactions=[]
    cmds= sorted(app.subCmds)
    for cmd in cmds:
        myactions.append(argparse._StoreAction(
            option_strings=[],
            dest=str(cmd),
            nargs=None,
            const=None,
            default=None,
            type=str,
            choices=None,
            required=False,
            help=str(app.subCmds[cmd].__doc__),
            metavar=None))
    return myactions 
開發者ID:usharesoft,項目名稱:hammr,代碼行數:18,代碼來源:hammr.py

示例3: add_arguments

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
def add_arguments(self, actions):
    """Adds arguments.

    Args:
      actions (list[argparse._StoreAction]): command line actions.
    """
    actions = sorted(actions, key=operator.attrgetter('option_strings'))
    super(SortedArgumentsHelpFormatter, self).add_arguments(actions) 
開發者ID:log2timeline,項目名稱:plaso,代碼行數:10,代碼來源:test_lib.py

示例4: __init__

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
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._StoreAction.__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)


# noinspection PyShadowingBuiltins,PyShadowingBuiltins 
開發者ID:TuuuNya,項目名稱:WebPocket,代碼行數:30,代碼來源:argparse_completer.py

示例5: kms_parser_get

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
def kms_parser_get(parser):
        zeroarg, onearg = ([] for _ in range(2))
        act = vars(parser)['_actions']
        for i in range(len(act)):
                if act[i].option_strings not in ([], ['-h', '--help']):
                        if isinstance(act[i], argparse._StoreAction):
                                onearg.append(act[i].option_strings)
                        else:
                                zeroarg.append(act[i].option_strings)
        return zeroarg, onearg 
開發者ID:SystemRage,項目名稱:py-kms,代碼行數:12,代碼來源:pykms_Misc.py

示例6: update_args

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
def update_args(args, arg_parser):
    for action in arg_parser._actions:
        if isinstance(action, argparse._StoreAction) or isinstance(action, argparse._StoreTrueAction) \
                or isinstance(action, argparse._StoreFalseAction):
            if not hasattr(args, action.dest):
                setattr(args, action.dest, action.default) 
開發者ID:pcyin,項目名稱:tranX,代碼行數:8,代碼來源:utils.py

示例7: is_argument_required

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
def is_argument_required(action):
    return isinstance(action, argparse._StoreAction) 
開發者ID:allegroai,項目名稱:trains-agent,代碼行數:4,代碼來源:complete.py

示例8: main

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
def main():

    if len(sys.argv) != 2:
        return 1

    comp_words = iter(sys.argv[1].split()[1:])

    parser = get_parser()

    seen = []
    for word in comp_words:
        if word in parser.choices:
            parser = parser[word]
            continue
        actions = {name: action for action in parser._actions for name in action.option_strings}
        first, _, rest = word.partition('=')
        is_one_word_store_action = rest and first in actions
        if is_one_word_store_action:
            word = first
        seen.append(word)
        try:
            action = actions[word]
        except KeyError:
            break
        if isinstance(action, argparse._StoreAction) and not isinstance(action, argparse._StoreConstAction):
            if not is_one_word_store_action:
                try:
                    next(comp_words)
                except StopIteration:
                    break

    options = list(parser.choices)

    options = [format_option(option, argument_required=False) for option in options]
    options.extend(get_options(parser))
    options = [option for option in options if option.rstrip('= ') not in seen]

    print('\n'.join(options))
    return 0 
開發者ID:allegroai,項目名稱:trains-agent,代碼行數:41,代碼來源:complete.py

示例9: get_parser_actions

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
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) 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:59,代碼來源:cli.py

示例10: format_cli

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
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) 
開發者ID:openaps,項目名稱:openaps,代碼行數:52,代碼來源:show.py

示例11: add_argument

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
def add_argument(self, *args, **kwargs):
    """
    This method supports the same args as ArgumentParser.add_argument(..)
    as well as the additional args below.

    Additional Args:
        env_var: If set, the value of this environment variable will override
            any config file or default values for this arg (but can itself
            be overriden on the commandline). Also, if auto_env_var_prefix is
            set in the constructor, this env var name will be used instead of
            the automatic name.
        is_config_file_arg: If True, this arg is treated as a config file path
            This provides an alternative way to specify config files in place of
            the ArgumentParser(fromfile_prefix_chars=..) mechanism.
            Default: False
        is_write_out_config_file_arg: If True, this arg will be treated as a
            config file path, and, when it is specified, will cause
            configargparse to write all current commandline args to this file
            as config options and then exit.
            Default: False
    """

    env_var = kwargs.pop("env_var", None)

    is_config_file_arg = kwargs.pop(
        "is_config_file_arg", None) or kwargs.pop(
        "is_config_file", None)  # for backward compat.

    is_write_out_config_file_arg = kwargs.pop(
        "is_write_out_config_file_arg", None)

    action = self.original_add_argument_method(*args, **kwargs)

    action.is_positional_arg = not action.option_strings
    action.env_var = env_var
    action.is_config_file_arg = is_config_file_arg
    action.is_write_out_config_file_arg = is_write_out_config_file_arg

    if action.is_positional_arg and env_var:
        raise ValueError("env_var can't be set for a positional arg.")
    if action.is_config_file_arg and type(action) != argparse._StoreAction:
        raise ValueError("arg with is_config_file_arg=True must have "
                         "action='store'")
    if action.is_write_out_config_file_arg:
        error_prefix = "arg with is_write_out_config_file_arg=True "
        if type(action) != argparse._StoreAction:
            raise ValueError(error_prefix + "must have action='store'")
        if is_config_file_arg:
            raise ValueError(error_prefix + "can't also have "
                                            "is_config_file_arg=True")

    return action 
開發者ID:DistributedSystemsGroup,項目名稱:zoe,代碼行數:54,代碼來源:configargparse.py

示例12: convert_item_to_command_line_arg

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
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 
開發者ID:gis-rpd,項目名稱:pipelines,代碼行數:51,代碼來源:configargparse.py

示例13: add_argument

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
def add_argument(self, *args, **kwargs):
    """
    This method supports the same args as ArgumentParser.add_argument(..)
    as well as the additional args below.

    Additional Args:
        env_var: If set, the value of this environment variable will override
            any config file or default values for this arg (but can itself
            be overriden on the commandline). Also, if auto_env_var_prefix is
            set in the constructor, this env var name will be used instead of
            the automatic name.
        is_config_file_arg: If True, this arg is treated as a config file path
            This provides an alternative way to specify config files in place of
            the ArgumentParser(fromfile_prefix_chars=..) mechanism.
            Default: False
        is_write_out_config_file_arg: If True, this arg will be treated as a
            config file path, and, when it is specified, will cause
            configargparse to write all current commandline args to this file
            as config options and then exit.
            Default: False
    """

    env_var = kwargs.pop("env_var", None)

    is_config_file_arg = kwargs.pop(
        "is_config_file_arg", None) or kwargs.pop(
        "is_config_file", None)  # for backward compat.

    is_write_out_config_file_arg = kwargs.pop(
        "is_write_out_config_file_arg", None)

    action = self.original_add_argument_method(*args, **kwargs)

    action.is_positional_arg = not action.option_strings
    action.env_var = env_var
    action.is_config_file_arg = is_config_file_arg
    action.is_write_out_config_file_arg = is_write_out_config_file_arg

    if action.is_positional_arg and env_var:
        raise ValueError("env_var can't be set for a positional arg.")
    if action.is_config_file_arg and not isinstance(action, argparse._StoreAction):
        raise ValueError("arg with is_config_file_arg=True must have "
                         "action='store'")
    if action.is_write_out_config_file_arg:
        error_prefix = "arg with is_write_out_config_file_arg=True "
        if not isinstance(action, argparse._StoreAction):
            raise ValueError(error_prefix + "must have action='store'")
        if is_config_file_arg:
                raise ValueError(error_prefix + "can't also have "
                                                "is_config_file_arg=True")

    return action 
開發者ID:gis-rpd,項目名稱:pipelines,代碼行數:54,代碼來源:configargparse.py

示例14: _add_to_defaults

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
def _add_to_defaults(cls, a_parser, defaults, a_args=None, a_namespace=None, a_parsed_args=None):
        actions = [
            a for a in a_parser._actions
            if isinstance(a, _StoreAction) or isinstance(a, _StoreConstAction)
        ]
        args_dict = {}
        try:
            if isinstance(a_parsed_args, dict):
                args_dict = a_parsed_args
            else:
                if a_parsed_args:
                    args_dict = a_parsed_args.__dict__
                else:
                    args_dict = call_original_argparser(a_parser, args=a_args, namespace=a_namespace).__dict__
            defaults_ = {
                a.dest: args_dict.get(a.dest) if (args_dict.get(a.dest) is not None) else ''
                for a in actions
            }
        except Exception:
            # don't crash us if we failed parsing the inputs
            defaults_ = {
                a.dest: a.default if a.default is not None else ''
                for a in actions
            }

        full_args_dict = copy(defaults)
        full_args_dict.update(args_dict)
        defaults.update(defaults_)

        # deal with sub parsers
        sub_parsers = [
            a for a in a_parser._actions
            if isinstance(a, _SubParsersAction)
        ]
        for sub_parser in sub_parsers:
            if sub_parser.dest and sub_parser.dest != SUPPRESS:
                defaults[sub_parser.dest] = full_args_dict.get(sub_parser.dest) or ''
            for choice in sub_parser.choices.values():
                # recursively parse
                defaults = cls._add_to_defaults(
                    a_parser=choice,
                    defaults=defaults,
                    a_parsed_args=a_parsed_args or full_args_dict
                )

        return defaults 
開發者ID:allegroai,項目名稱:trains,代碼行數:48,代碼來源:args.py

示例15: convert_item_to_command_line_arg

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _StoreAction [as 別名]
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 
開發者ID:bw2,項目名稱:ConfigArgParse,代碼行數:60,代碼來源:configargparse.py


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