本文整理汇总了Python中argparse.Action方法的典型用法代码示例。如果您正苦于以下问题:Python argparse.Action方法的具体用法?Python argparse.Action怎么用?Python argparse.Action使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类argparse
的用法示例。
在下文中一共展示了argparse.Action方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: cli_skip_missing_interpreter
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def cli_skip_missing_interpreter(parser):
class SkipMissingInterpreterAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
value = "true" if values is None else values
if value not in ("config", "true", "false"):
raise argparse.ArgumentTypeError("value must be config, true or false")
setattr(namespace, self.dest, value)
parser.add_argument(
"-s",
"--skip-missing-interpreters",
default="config",
metavar="val",
nargs="?",
action=SkipMissingInterpreterAction,
help="don't fail tests for missing interpreters: {config,true,false} choice",
)
示例2: pytest_addoption
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def pytest_addoption(parser):
group = parser.getgroup("sqlalchemy")
def make_option(name, **kw):
callback_ = kw.pop("callback", None)
if callback_:
class CallableAction(argparse.Action):
def __call__(self, parser, namespace,
values, option_string=None):
callback_(option_string, values, parser)
kw["action"] = CallableAction
group.addoption(name, **kw)
plugin_base.setup_options(make_option)
plugin_base.read_config()
示例3: test
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def test(self):
def get_my_type(string):
return 'my_type{%s}' % string
parser = argparse.ArgumentParser()
parser.register('type', 'my_type', get_my_type)
parser.add_argument('-x', type='my_type')
parser.add_argument('y', type='my_type')
self.assertEqual(parser.parse_args('1'.split()),
NS(x=None, y='my_type{1}'))
self.assertEqual(parser.parse_args('-x 1 42'.split()),
NS(x='my_type{1}', y='my_type{42}'))
# ============
# Action tests
# ============
示例4: make_datalab_help_action
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def make_datalab_help_action(self):
"""Custom action for --datalab-help.
The action output the package specific parameters and will be part of "%%ml train"
help string.
"""
datalab_help = self.datalab_help
epilog = self.datalab_epilog
class _CustomAction(argparse.Action):
def __init__(self, option_strings, dest, help=None):
super(_CustomAction, self).__init__(
option_strings=option_strings, dest=dest, nargs=0, help=help)
def __call__(self, parser, args, values, option_string=None):
print('\n\n'.join(datalab_help))
if epilog:
print(epilog)
# We have printed all help string datalab needs. If we don't quit, it will complain about
# missing required arguments later.
quit()
return _CustomAction
示例5: get_argparse_extension_checker
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def get_argparse_extension_checker(choices, dir_allowed=False):
"""Get an :class:`argparge.Action` class that can check for correct extensions.
Returns:
argparse.Action: a class (not an instance) of an argparse action.
"""
class Act(argparse.Action):
def __call__(self, parser, namespace, fname, option_string=None):
is_valid = any(map(lambda choice: fname[-len(choice):] == choice, choices))
if not is_valid and dir_allowed and os.path.isdir(fname):
is_valid = True
if is_valid:
setattr(namespace, self.dest, fname)
else:
option_string = '({})'.format(option_string) if option_string else ''
parser.error("File doesn't end with one of {}{}".format(choices, option_string))
return Act
示例6: add_version_alias
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def add_version_alias(parser):
"""
Add --version as a (hidden) alias for the version command.
It's not uncommon to blindly run a command with --version as the sole
argument, so its useful to make that Just Work.
"""
class run_version_command(argparse.Action):
def __call__(self, *args, **kwargs):
opts = SimpleNamespace()
sys.exit( version.run(opts) )
return parser.add_argument(
"--version",
nargs = 0,
help = argparse.SUPPRESS,
action = run_version_command)
示例7: storeBool
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def storeBool(boolDefault, ep):
class _StoreBoolAction(argparse.Action):
def __init__(self, option_strings, dest, help=None):
super(_StoreBoolAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
const=boolDefault,
default=False,
required=False,
help=help,
)
def __call__(self, parser, namespace, values, option_string=None):
ep.cs[self.dest] = self.const
ep.settingsProvidedOnCommandLine.append(self.dest)
ep.cs.failOnLoad()
return _StoreBoolAction
示例8: setSetting
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def setSetting(ep):
class _SetSettingAction(argparse.Action):
"""This class loads the command line supplied setting values into the
:py:data:`armi.settings.cs`
"""
def __call__(self, parser, namespace, values, option_string=None):
ep.cs[self.dest] = values # correctly converts type
ep.settingsProvidedOnCommandLine.append(self.dest)
ep.cs.failOnLoad()
return _SetSettingAction
# Q: Why does this require special treatment? Why not treat it like the other
# case settings and use setSetting action?
# A: Because caseTitle is no longer an actual cs setting. It's a instance attr.
示例9: assembleConfigHelps
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def assembleConfigHelps(self, pdlist, type, main):
class customArgsAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
main.quietMode = True
main.init_quietMode()
main.prepareBuilding(64)
main.build_mingw(64)
main.initBuildFolders()
for k, v in pdlist.items():
if '_disabled' not in v:
if '_info' in v:
beforePath = os.getcwd()
path = main.getPackagePath(k, v, type)
main.cchdir(path)
if os.path.isfile(os.path.join(path, "configure")):
os.system("./configure --help")
if os.path.isfile(os.path.join(path, "waf")):
os.system("./waf --help")
main.cchdir(beforePath)
print("-------------------")
setattr(args, self.dest, values)
parser.exit()
return customArgsAction
示例10: __call__
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def __call__(
self,
parser, # type: argparse.ArgumentParser
namespace, # type: argparse.Namespace
values, # type: Union[ARGPARSE_TEXT, Sequence[Any], None]
option_string=None, # type: Optional[ARGPARSE_TEXT]
):
# type: (...) -> None
"""Checks to make sure that the destination is empty before writing.
:raises parser.error: if destination is already set
"""
if getattr(namespace, self.dest) is not None: # type: ignore # typeshed doesn't know about Action.dest yet?
parser.error("{} argument may not be specified more than once".format(option_string))
return
setattr(namespace, self.dest, values) # type: ignore # typeshed doesn't know about Action.dest yet?
示例11: choices_with_default
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def choices_with_default(choices, default):
"""This closure defines an argparser custom action that ensures an argument
value is in a list of choices, and if not, sets the argument to a default
value.
Implementing this argparser action instead of using only a 'choices' list
for the argument works better for a script called from Jamf where an
optional parameter may be omitted from the policy definition, but
subsequent parameters are passed, ie. script.py 1 2 3 [omitted] 5 6
"""
class customAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if (values in choices) or (values == default):
setattr(args, self.dest, values)
else:
setattr(args, self.dest, default)
return customAction
示例12: load_config
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def load_config(self):
"""Load the config file optionally given by --config argument
Return the string read from sys.argv, with '--config
<config-file>' removed
"""
parser = argparse.ArgumentParser(add_help=False)
class _ConfigAction(argparse.Action):
def __call__(self, parser, namespace, value, option_string=None):
if not os.path.isfile(value):
raise IOError(
'configuration file not found {}'.format(value))
print('loading configuration from {}'.format(value))
utils.config.read(value)
# add a configuration argument
parser.add_argument(
'-c', '--config', metavar='<config-file>', action=_ConfigAction)
return parser.parse_known_args()[1]
示例13: add_argument_os_code_name_and_arch_tuples
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def add_argument_os_code_name_and_arch_tuples(parser, required=True):
class _AddUbuntuTupleAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
import sys
print('WARNING: ' + self.help, file=sys.stderr)
for value in values:
if value.count(':') != 1:
raise argparse.ArgumentError(
argument=self,
message='expected 2 parts separated by colons')
setattr(
args, 'os_name_and_os_code_name_and_arch_tuples',
[('ubuntu:' + value).split(':') for value in values])
setattr(args, self.dest, values)
parser.add_argument(
'--os-code-name-and-arch-tuples',
nargs='+',
required=required, action=_AddUbuntuTupleAction,
help="DEPRECATED: Use '--os-name-and-os-code-name-and-arch-tuples'")
示例14: get_constrained_float_action
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def get_constrained_float_action(
min_val: Optional[float] = None, max_val: Optional[float] = None
) -> Type[argparse.Action]:
class ConstrainedFloatAction(argparse.Action):
"""Custom action for ensuring floats arguments meet these."""
def __call__(self, parser, namespace, values, option_string=None): # type: ignore
if min_val is not None and values < min_val:
parser.error("{0} must be no smaller than {1}.".format(option_string, min_val))
if max_val is not None and values > max_val:
parser.error("{0} must be no greater than {1}.".format(option_string, max_val))
setattr(namespace, self.dest, values)
return ConstrainedFloatAction
示例15: _get_parent_class
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import Action [as 别名]
def _get_parent_class(self, **kwargs):
# wrap any existing action
action = kwargs.get('action', None)
parent_class = argparse.Action
# action is either a user-defined Action class or a string referring a library-defined Action
if isinstance(action, type) and issubclass(action, argparse.Action):
parent_class = action
elif isinstance(action, str):
parent_class = self.command_loader.cli_ctx.invocation.parser._registries['action'][action] # pylint: disable=protected-access
return parent_class