def __call__(self, parser, namespace, values, option_string=None):
parser.print_help()
print('')
# retrieve subparsers from parser
subparsers_actions = [
action for action in parser._actions
if isinstance(action, argparse._SubParsersAction)]
for subparsers_action in subparsers_actions:
# get all subparsers and print help
for choice, subparser in subparsers_action.choices.items():
print('Subcommand \'{0}\':'.format(choice))
subparser.print_help()
print(
'example: confidant get_service -u'
' "https://confidant-production.example.com" -k'
' "alias/authnz-production" --from myservice-production'
' --to confidant-production --user_type service'
' --region us-west-2 --service myservice-production'
)
parser.exit()
python类_SubParsersAction()的实例源码
def add_subparser(self, name: str, parser: argparse._SubParsersAction) -> argparse.ArgumentParser:
# pylint: disable=protected-access
description = '''Train the specified model on the specified dataset.'''
subparser = parser.add_parser(
name, description=description, help='Train a model')
subparser.add_argument('param_path',
type=str,
help='path to parameter file describing the model to be trained')
# This is necessary to preserve backward compatibility
serialization = subparser.add_mutually_exclusive_group(required=True)
serialization.add_argument('-s', '--serialization-dir',
type=str,
help='directory in which to save the model and its logs')
serialization.add_argument('--serialization_dir',
type=str,
help=argparse.SUPPRESS)
subparser.set_defaults(func=train_model_from_args)
return subparser
def __call__(self, parser, namespace, values, option_string=None):
parser.print_help()
print()
# retrieve subparsers from parser
subparsers_actions = [
action for action in parser._actions
if isinstance(action, argparse._SubParsersAction)]
# there will probably only be one subparser_action,
# but better save than sorry
for subparsers_action in subparsers_actions:
# get all subparsers and print help
for choice, subparser in subparsers_action.choices.items():
print("Action '{}'".format(choice))
print(subparser.format_help())
parser.exit()
def get_form_inputs(self, parser=None, prefix=[]):
inputs = []
if parser is None:
parser = self._parser
group_actions = [group_actions
for group_actions in parser._mutually_exclusive_groups]
actions = [action
for action in parser._actions
if action not in group_actions]
for action in actions:
if not self.filter_input_object(action):
inputs.append(self.get_input_object(action, prefix))
if isinstance(action, argparse._SubParsersAction):
for choice_name, choice_parser in action.choices.items():
inputs.extend(self.get_form_inputs(choice_parser, prefix + [choice_name]))
return inputs
def gen_parser(caller, commands, parser, subparsers):
"""
Run setup() for all submodules of sub_commands
:param caller: Module calling this module
:type caller: string
:param commands: Sub-module relative to caller with commands
:type commands: string
:param parser: Argparse object
:type parser: argparse.ArgumentParser
:param subparsers: Subparsers object
:type subparsers: argparse._SubParsersAction
"""
package = importlib.import_module('{}.{}'.format(caller, commands))
for importer, modname, ispkg in \
pkgutil.iter_modules(package.__path__,
prefix='{}.{}.'.format(caller, commands)):
if not ispkg:
found_module = importlib.import_module('{}'.format(modname))
found_module.setup(parser, subparsers)
# vim:et:fdm=marker:sts=4:sw=4:ts=4
def _iter_indented_subactions(self, action):
"""
Sort the subcommands alphabetically
"""
try:
get_subactions = action._get_subactions
except AttributeError:
pass
else:
self._indent()
if isinstance(action, argparse._SubParsersAction):
for subaction in sorted(
get_subactions(), key=lambda x: x.dest):
yield subaction
else:
for subaction in get_subactions():
yield subaction
self._dedent()
def get_subparsers(parser, create=False):
"""
Returns the :class:`argparse._SubParsersAction` instance for given
:class:`ArgumentParser` instance as would have been returned by
:meth:`ArgumentParser.add_subparsers`. The problem with the latter is that
it only works once and raises an exception on the second attempt, and the
public API seems to lack a method to get *existing* subparsers.
:param create:
If `True`, creates the subparser if it does not exist. Default if
`False`.
"""
# note that ArgumentParser._subparsers is *not* what is returned by
# ArgumentParser.add_subparsers().
if parser._subparsers:
actions = [a for a in parser._actions
if isinstance(a, argparse._SubParsersAction)]
assert len(actions) == 1
return actions[0]
else:
if create:
return parser.add_subparsers()
def set_default_subparser(self, name, args=None):
"""
see http://stackoverflow.com/questions/5176691/argparse-how-to-specify-a-default-subcommand
"""
subparser_found = False
for arg in sys.argv[1:]:
if arg in ['-h', '--help']: # global help if no subparser
break
else:
for x in self._subparsers._actions:
if not isinstance(x, argparse._SubParsersAction):
continue
for sp_name in x._name_parser_map.keys():
if sp_name in sys.argv[1:]:
subparser_found = True
if not subparser_found:
# insert default in first position, this implies no
# global options without a sub_parsers specified
if args is None:
sys.argv.insert(1, name)
else:
args.insert(0, name)
def _format_action(self, action):
if type(action) == argparse._SubParsersAction:
# calculate the subcommand max length
subactions = action._get_subactions()
invocations = [self._format_action_invocation(a)
for a in subactions]
self._subcommand_max_length = max(len(i) for i in invocations)
if type(action) == argparse._SubParsersAction._ChoicesPseudoAction:
# format subcommand help line
subcommand = self._format_action_invocation(action)
help_text = self._expand_help(action)
return (" {:{width}}\t\t{} \n").format(
subcommand, help_text, width=self._subcommand_max_length)
elif type(action) == argparse._SubParsersAction:
# eliminate subcommand choices line {cmd1, cmd2}
msg = ''
for subaction in action._get_subactions():
msg += self._format_action(subaction)
return msg
else:
return super(SimpleHelpFormatter, self)._format_action(action)
def __call__(self, parser, namespace, values, option_string=None):
parser.print_help()
# retrieve subparsers from parser
subparsers_actions = [
action for action in parser._actions
if isinstance(action, argparse._SubParsersAction)]
for subparsers_action in subparsers_actions:
# get all subparsers and print help
print
for choice, subparser in subparsers_action.choices.items():
print(choice)
print('*'*len(choice))
print(subparser.format_help())
parser.exit()
def set_default_subparser(self, name, args=None):
"""default subparser selection. Call after setup, just before parse_args()
name: is the name of the subparser to call by default
args: if set is the argument list handed to parse_args()
, tested with 2.7, 3.2, 3.3, 3.4
it works with 2.6 assuming argparse is installed
"""
subparser_found = False
for arg in sys.argv[1:]:
if arg in ['-h', '--help']: # global help if no subparser
break
else:
for x in self._subparsers._actions:
if not isinstance(x, argparse._SubParsersAction):
continue
for sp_name in x._name_parser_map.keys():
if sp_name in sys.argv[1:]:
subparser_found = True
if not subparser_found:
# insert default in first position, this implies no
# global options without a sub_parsers specified
if args is None:
sys.argv.insert(1, name)
else:
args.insert(0, name)
def _add_permission_subparsers(self, subparser: _SubParsersAction, parser_class: Type[CommandParser]) -> None:
group_parser = subparser.add_parser("group", help="Manage group permissions (unimplemented)")
group_sp = group_parser.add_subparsers(title="Manage group permissions (unimplemented)",
parser_class=parser_class,
dest="accesssubcmd") # type: _SubParsersAction
user_parser = subparser.add_parser("user", help="Manage user permissions (unimplemented)")
user_sp = user_parser.add_subparsers(title="Manage user permissions (unimplemented)",
parser_class=parser_class,
dest="accesssubcmd") # type: _SubParsersAction
def create_allow_deny_cmds(localsubparser: _SubParsersAction, entity_name: str) -> None:
allow_p = localsubparser.add_parser("allow", help="Give a %s access" % entity_name) # type: CommandParser
allow_p.add_argument("--name", dest="name", default=None,
help="Find %s by name." % entity_name)
deny_p = localsubparser.add_parser("deny", help="Deny a %s access" % entity_name) # type: CommandParser
deny_p.add_argument("--name", dest="name", default=None,
help="Find %s by name." % entity_name)
list_p = localsubparser.add_parser("list", help="List all %ss" % entity_name) # type: CommandParser
create_allow_deny_cmds(group_sp, "group")
create_allow_deny_cmds(user_sp, "user")
def argparse_to_ini(parser, root_section='lago', incl_unset=False):
subparsers_actions = [
action for action in parser._actions
if isinstance(action, argparse._SubParsersAction)
]
root_actions = [
action for action in parser._actions
if not isinstance(action, argparse._SubParsersAction)
]
cp = configparser.ConfigParser(allow_no_value=True)
_add_subparser_to_cp(cp, root_section, root_actions, incl_unset)
for subparsers_action in subparsers_actions:
for choice, subparser in subparsers_action.choices.items():
_add_subparser_to_cp(cp, choice, subparser._actions, incl_unset)
header = '# Lago configuration file, generated: {0}'.format(
time.strftime("%c")
)
with StringIO() as ini_str:
cp.write(ini_str)
return '\n'.join([header, ini_str.getvalue()])
def add_subparser(self, name: str, parser: argparse._SubParsersAction) -> argparse.ArgumentParser:
# pylint: disable=protected-access
raise NotImplementedError
def add_subparser(self, name: str, parser: argparse._SubParsersAction) -> argparse.ArgumentParser:
# pylint: disable=protected-access
description = '''Evaluate the specified model + dataset'''
subparser = parser.add_parser(
name, description=description, help='Evaluate the specified model + dataset')
archive_file = subparser.add_mutually_exclusive_group(required=True)
archive_file.add_argument('--archive-file', type=str, help='path to an archived trained model')
archive_file.add_argument('--archive_file', type=str, help=argparse.SUPPRESS)
evaluation_data_file = subparser.add_mutually_exclusive_group(required=True)
evaluation_data_file.add_argument('--evaluation-data-file',
type=str,
help='path to the file containing the evaluation data')
evaluation_data_file.add_argument('--evaluation_data_file',
type=str,
help=argparse.SUPPRESS)
cuda_device = subparser.add_mutually_exclusive_group(required=False)
cuda_device.add_argument('--cuda-device',
type=int,
default=-1,
help='id of GPU to use (if any)')
cuda_device.add_argument('--cuda_device', type=int, help=argparse.SUPPRESS)
subparser.add_argument('-o', '--overrides',
type=str,
default="",
help='a HOCON structure used to override the experiment configuration')
subparser.set_defaults(func=evaluate_from_args)
return subparser
def add_subparser(self, name: str, parser: argparse._SubParsersAction) -> argparse.ArgumentParser:
# pylint: disable=protected-access
description = '''Run the specified model against a JSON-lines input file.'''
subparser = parser.add_parser(
name, description=description, help='Use a trained model to make predictions.')
subparser.add_argument('archive_file', type=str, help='the archived model to make predictions with')
subparser.add_argument('input_file', type=argparse.FileType('r'), help='path to input file')
subparser.add_argument('--output-file', type=argparse.FileType('w'), help='path to output file')
batch_size = subparser.add_mutually_exclusive_group(required=False)
batch_size.add_argument('--batch-size', type=int, default=1, help='The batch size to use for processing')
batch_size.add_argument('--batch_size', type=int, help=argparse.SUPPRESS)
subparser.add_argument('--silent', action='store_true', help='do not print output to stdout')
cuda_device = subparser.add_mutually_exclusive_group(required=False)
cuda_device.add_argument('--cuda-device', type=int, default=-1, help='id of GPU to use (if any)')
cuda_device.add_argument('--cuda_device', type=int, help=argparse.SUPPRESS)
subparser.add_argument('-o', '--overrides',
type=str,
default="",
help='a HOCON structure used to override the experiment configuration')
subparser.set_defaults(func=_predict(self.predictors))
return subparser
def add_subparser(self, name: str, parser: argparse._SubParsersAction) -> argparse.ArgumentParser:
# pylint: disable=protected-access
description = '''Run the web service, which provides an HTTP API as well as a web demo.'''
subparser = parser.add_parser(
name, description=description, help='Run the web service and demo.')
subparser.add_argument('--port', type=int, default=8000)
subparser.set_defaults(func=_serve(self.trained_models))
return subparser
def test_parser(self):
parser = cli._get_parser(gitlab.v3.cli)
subparsers = None
for action in parser._actions:
if type(action) == argparse._SubParsersAction:
subparsers = action
break
self.assertIsNotNone(subparsers)
self.assertIn('user', subparsers.choices)
user_subparsers = None
for action in subparsers.choices['user']._actions:
if type(action) == argparse._SubParsersAction:
user_subparsers = action
break
self.assertIsNotNone(user_subparsers)
self.assertIn('list', user_subparsers.choices)
self.assertIn('get', user_subparsers.choices)
self.assertIn('delete', user_subparsers.choices)
self.assertIn('update', user_subparsers.choices)
self.assertIn('create', user_subparsers.choices)
self.assertIn('block', user_subparsers.choices)
self.assertIn('unblock', user_subparsers.choices)
actions = user_subparsers.choices['create']._option_string_actions
self.assertFalse(actions['--twitter'].required)
self.assertTrue(actions['--username'].required)
def set_default_subparser(self, name, args=None):
"""default subparser selection. Call after setup, just before parse_args()
name: is the name of the subparser to call by default
args: if set is the argument list handed to parse_args()
, tested with 2.7, 3.2, 3.3, 3.4
it works with 2.6 assuming argparse is installed
"""
subparser_found = False
for arg in sys.argv[1:]:
if arg in ['-h', '--help']: # global help if no subparser
break
else:
for x in self._subparsers._actions:
if not isinstance(x, argparse._SubParsersAction):
continue
for sp_name in x._name_parser_map.keys():
if sp_name in sys.argv[1:]:
subparser_found = True
if not subparser_found:
# insert default in first position, this implies no
# global options without a sub_parsers specified
if args is None:
sys.argv.insert(1, name)
else:
args.insert(0, name)
def get_subparsers(parser):
'''get_subparser will get a dictionary of subparsers, to help with printing help
'''
actions = [action for action in parser._actions
if isinstance(action, argparse._SubParsersAction)]
subparsers = dict()
for action in actions:
# get all subparsers and print help
for choice, subparser in action.choices.items():
subparsers[choice] = subparser
return subparsers
def get_subparser(self, action):
return isinstance(action, argparse._SubParsersAction)
def get_parser(description):
"""
Returns argparse object with commands
:param description: Description for Argparse
:type description: string
:returns: Argparse of object, and Subparser object
:rtype: argparse.ArgumentParser, argparse._SubParsersAction
"""
parser = argparse.ArgumentParser(description=description)
subparsers = parser.add_subparsers(dest='command')
return parser, subparsers
def get_subparsers(parser):
'''get_subparser will get a dictionary of subparsers, to help with printing help
'''
actions = [action for action in parser._actions
if isinstance(action, argparse._SubParsersAction)]
subparsers = dict()
for action in actions:
# get all subparsers and print help
for choice, subparser in action.choices.items():
subparsers[choice] = subparser
return subparsers
def get_subparsers(parser):
'''get_subparser will get a dictionary of subparsers, to help with printing help
'''
actions = [action for action in parser._actions
if isinstance(action, argparse._SubParsersAction)]
subparsers = dict()
for action in actions:
# get all subparsers and print help
for choice, subparser in action.choices.items():
subparsers[choice] = subparser
return subparsers
def parse_args(self, *args, **kwargs): # pylint: disable=arguments-differ
# hack for tests
app = kwargs.pop('app', None)
namespace = super(QubesArgumentParser, self).parse_args(*args, **kwargs)
if self._want_app and not self._want_app_no_instance:
self.set_qubes_verbosity(namespace)
if app is not None:
namespace.app = app
else:
namespace.app = qubesadmin.Qubes()
for action in self._actions:
# pylint: disable=protected-access
if issubclass(action.__class__, QubesAction):
action.parse_qubes_app(self, namespace)
elif issubclass(action.__class__,
argparse._SubParsersAction): # pylint: disable=no-member
assert hasattr(namespace, 'command')
command = namespace.command
if command is None:
continue
subparser = action._name_parser_map[command]
for subaction in subparser._actions:
if issubclass(subaction.__class__, QubesAction):
subaction.parse_qubes_app(self, namespace)
return namespace
def set_default_subparser(self, name, args=None):
"""default subparser selection. Call after setup, just before parse_args()
name: is the name of the subparser to call by default
args: if set is the argument list handed to parse_args()
, tested with 2.7, 3.2, 3.3, 3.4
it works with 2.6 assuming argparse is installed
"""
subparser_found = False
for arg in sys.argv[1:]:
if arg in ['-h', '--help']: # global help if no subparser
break
else:
for x in self._subparsers._actions:
if not isinstance(x, argparse._SubParsersAction):
continue
for sp_name in x._name_parser_map.keys():
if sp_name in sys.argv[1:]:
subparser_found = True
if not subparser_found:
# insert default in first position, this implies no
# global options without a sub_parsers specified
if args is None:
sys.argv.insert(1, name)
else:
args.insert(0, name)
def _format_action(self, action):
parts = super(HelpFormatter, self)._format_action(action)
# pop off subparser header line
if isinstance(action, argparse._SubParsersAction):
parts = "\n".join(parts.split('\n')[1:])
return parts
def show_subparser_help(subparser_name):
'''
Function returns help message for subparser
'''
subparsers_actions = [
action for action in parser._actions
if isinstance(action, argparse._SubParsersAction)]
return subparsers_actions[0].choices[subparser_name].format_help()
def _get_subparsers(self):
"""Recursively get subparsers."""
subparsers = []
for action in self._actions:
if isinstance(action, argparse._SubParsersAction):
for _, subparser in action.choices.items():
subparsers.append(subparser)
ret = subparsers
for sp in subparsers:
ret += sp._get_subparsers()
return ret
def _iter_indented_subactions(self, action):
try:
get_subactions = action._get_subactions
except AttributeError:
pass
else:
self._indent()
if isinstance(action, argparse._SubParsersAction):
for subaction in sorted(get_subactions(), key=lambda x: x.dest):
yield subaction
else:
for subaction in get_subactions():
yield subaction
self._dedent()