Python argparse._StoreAction() Examples
The following are 16
code examples of argparse._StoreAction().
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 |
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: hammr.py From hammr with Apache License 2.0 | 6 votes |
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
Example #3
Source File: test_lib.py From plaso with Apache License 2.0 | 5 votes |
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)
Example #4
Source File: argparse_completer.py From WebPocket with GNU General Public License v3.0 | 5 votes |
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
Example #5
Source File: pykms_Misc.py From py-kms with The Unlicense | 5 votes |
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
Example #6
Source File: utils.py From tranX with Apache License 2.0 | 5 votes |
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)
Example #7
Source File: complete.py From trains-agent with Apache License 2.0 | 5 votes |
def is_argument_required(action): return isinstance(action, argparse._StoreAction)
Example #8
Source File: complete.py From trains-agent with Apache License 2.0 | 5 votes |
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
Example #9
Source File: cli.py From mutatest with MIT License | 4 votes |
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 #10
Source File: show.py From openaps with MIT License | 4 votes |
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 #11
Source File: configargparse.py From zoe with Apache License 2.0 | 4 votes |
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
Example #12
Source File: configargparse.py From pipelines with MIT License | 4 votes |
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 #13
Source File: configargparse.py From pipelines with MIT License | 4 votes |
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
Example #14
Source File: args.py From trains with Apache License 2.0 | 4 votes |
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
Example #15
Source File: configargparse.py From ConfigArgParse with MIT License | 4 votes |
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
Example #16
Source File: configargparse.py From ConfigArgParse with MIT License | 4 votes |
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