本文整理汇总了Python中argparse._AppendAction方法的典型用法代码示例。如果您正苦于以下问题:Python argparse._AppendAction方法的具体用法?Python argparse._AppendAction怎么用?Python argparse._AppendAction使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类argparse
的用法示例。
在下文中一共展示了argparse._AppendAction方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_get_parser_actions
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _AppendAction [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
示例2: __init__
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _AppendAction [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._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)
示例3: add_dynamic_attr
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _AppendAction [as 别名]
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]
示例4: convert_item_to_command_line_arg
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _AppendAction [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 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
示例5: get_parser_actions
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _AppendAction [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)
示例6: parse_ini_config_with_cli
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _AppendAction [as 别名]
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
####################################################################################################
示例7: format_cli
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _AppendAction [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)
示例8: convert_item_to_command_line_arg
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _AppendAction [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
示例9: convert_item_to_command_line_arg
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _AppendAction [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