本文整理汇总了Python中argparse._StoreTrueAction方法的典型用法代码示例。如果您正苦于以下问题:Python argparse._StoreTrueAction方法的具体用法?Python argparse._StoreTrueAction怎么用?Python argparse._StoreTrueAction使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类argparse
的用法示例。
在下文中一共展示了argparse._StoreTrueAction方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_get_parser_actions
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _StoreTrueAction [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: _maybe_apply_flag
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _StoreTrueAction [as 别名]
def _maybe_apply_flag(action, flags):
flag_name = _flag_name(action)
if not flag_name:
log.debug("skipping %s - not a flag option", action)
return
if not isinstance(action, action_types):
log.debug("skipping %s - not an action type", action)
return
flags[flag_name] = attrs = {}
if action.help:
attrs["description"] = action.help
if action.default is not None:
attrs["default"] = _ensure_json_encodable(action.default, flag_name)
if action.choices:
attrs["choices"] = _ensure_json_encodable(action.choices, flag_name)
if action.required:
attrs["required"] = True
if isinstance(action, argparse._StoreTrueAction):
attrs["arg-switch"] = True
elif isinstance(action, argparse._StoreFalseAction):
attrs["arg-switch"] = False
log.debug("added flag %r: %r", flag_name, attrs)
示例3: update_args
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _StoreTrueAction [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)
示例4: add_dynamic_attr
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _StoreTrueAction [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]
示例5: convert_setting_to_command_line_arg
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _StoreTrueAction [as 别名]
def convert_setting_to_command_line_arg(self, action, key, value):
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]
if isinstance(action, argparse._StoreTrueAction):
if value is True:
args.append(command_line_key)
elif isinstance(action, argparse._StoreFalseAction):
if value is False:
args.append(command_line_key)
elif isinstance(action, argparse._StoreConstAction):
if value == action.const:
args.append(command_line_key)
elif isinstance(action, argparse._CountAction):
for _ in range(value):
args.append(command_line_key)
elif action is not None and value == action.default:
pass
elif isinstance(value, list):
args.append(command_line_key)
args.extend([str(e) for e in value])
else:
args.append(command_line_key)
args.append(str(value))
return args
示例6: get_parser_actions
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _StoreTrueAction [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)
示例7: parse_ini_config_with_cli
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _StoreTrueAction [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
####################################################################################################
示例8: format_cli
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _StoreTrueAction [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)
示例9: _process_args_to_opts
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import _StoreTrueAction [as 别名]
def _process_args_to_opts(self, args_that_override: Optional[List[str]] = None):
self.opt = Opt(vars(self.args))
# custom post-parsing
self.opt['parlai_home'] = self.parlai_home
self.opt = self._infer_datapath(self.opt)
# set all arguments specified in command line as overridable
option_strings_dict = {}
store_true = []
store_false = []
for group in self._action_groups:
for a in group._group_actions:
if hasattr(a, 'option_strings'):
for option in a.option_strings:
option_strings_dict[option] = a.dest
if '_StoreTrueAction' in str(type(a)):
store_true.append(option)
elif '_StoreFalseAction' in str(type(a)):
store_false.append(option)
if args_that_override is None:
args_that_override = _sys.argv[1:]
for i in range(len(args_that_override)):
if args_that_override[i] in option_strings_dict:
if args_that_override[i] in store_true:
self.overridable[option_strings_dict[args_that_override[i]]] = True
elif args_that_override[i] in store_false:
self.overridable[option_strings_dict[args_that_override[i]]] = False
elif (
i < len(args_that_override) - 1
and args_that_override[i + 1][:1] != '-'
):
key = option_strings_dict[args_that_override[i]]
self.overridable[key] = self.opt[key]
self.opt['override'] = self.overridable
# load opts if a file is provided.
if self.opt.get('init_opt', None) is not None:
self._load_opts(self.opt)
# map filenames that start with 'zoo:' to point to the model zoo dir
options_to_change = {'model_file', 'dict_file', 'bpe_vocab', 'bpe_merge'}
for each_key in options_to_change:
if self.opt.get(each_key) is not None:
self.opt[each_key] = modelzoo_path(
self.opt.get('datapath'), self.opt[each_key]
)
if self.opt['override'].get(each_key) is not None:
# also check override
self.opt['override'][each_key] = modelzoo_path(
self.opt.get('datapath'), self.opt['override'][each_key]
)
# add start time of an experiment
self.opt['starttime'] = datetime.datetime.today().strftime('%b%d_%H-%M')