Python argparse._SubParsersAction() Examples

The following are code examples for showing how to use argparse._SubParsersAction(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: python-confidant-client   Author: lyft   File: cli.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 2
Project: allennlp   Author: allenai   File: train.py    (license) View Source Project 6 votes vote down vote up
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 
Example 3
Project: flickrsync   Author: danchal   File: helpaction.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 4
Project: argparseweb   Author: nirizr   File: page.py    (license) View Source Project 6 votes vote down vote up
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 
Example 5
Project: helcli   Author: sunshinekitty   File: parser.py    (license) View Source Project 6 votes vote down vote up
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 
Example 6
Project: ga4gh-common   Author: ga4gh   File: cli.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 7
Project: siphon-cli   Author: getsiphon   File: utils.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 8
Project: lbryum   Author: lbryio   File: commands.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 9
Project: ubuntu-image   Author: CanonicalLtd   File: __main__.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 10
Project: debpackager   Author: urban48   File: main.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 11
Project: random-episode   Author: Nekmo   File: management.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 12
Project: authserver   Author: jdelic   File: dockerauth.py    (license) View Source Project 6 votes vote down vote up
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") 
Example 13
Project: lago   Author: lago-project   File: utils.py    (license) View Source Project 6 votes vote down vote up
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()]) 
Example 14
Project: allennlp   Author: allenai   File: subcommand.py    (license) View Source Project 5 votes vote down vote up
def add_subparser(self, name: str, parser: argparse._SubParsersAction) -> argparse.ArgumentParser:
        # pylint: disable=protected-access
        raise NotImplementedError 
Example 15
Project: allennlp   Author: allenai   File: evaluate.py    (license) View Source Project 5 votes vote down vote up
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 
Example 16
Project: allennlp   Author: allenai   File: predict.py    (license) View Source Project 5 votes vote down vote up
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 
Example 17
Project: allennlp   Author: allenai   File: serve.py    (license) View Source Project 5 votes vote down vote up
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 
Example 18
Project: BoerOPS   Author: BoerOPS   File: test_cli.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 19
Project: weevely3-stealth   Author: edibledinos   File: argparsers.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 20
Project: som   Author: vsoch   File: __init__.py    (license) View Source Project 5 votes vote down vote up
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 
Example 21
Project: argparseweb   Author: nirizr   File: page.py    (license) View Source Project 5 votes vote down vote up
def get_subparser(self, action):
    return isinstance(action, argparse._SubParsersAction) 
Example 22
Project: helcli   Author: sunshinekitty   File: parser.py    (license) View Source Project 5 votes vote down vote up
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 
Example 23
Project: singularity-python   Author: singularityware   File: __init__.py    (license) View Source Project 5 votes vote down vote up
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 
Example 24
Project: singularity-python   Author: singularityware   File: __init__.py    (license) View Source Project 5 votes vote down vote up
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 
Example 25
Project: qubes-core-admin-client   Author: QubesOS   File: __init__.py    (license) View Source Project 5 votes vote down vote up
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 
Example 26
Project: simple-monitor-alert   Author: Nekmo   File: management.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 27
Project: giraffez   Author: capitalone   File: parser.py    (license) View Source Project 5 votes vote down vote up
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 
Example 28
Project: pyneng-examples-exercises   Author: natenka   File: parse_dhcp_snooping.py    (license) View Source Project 5 votes vote down vote up
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() 
Example 29
Project: pydatalab   Author: googledatalab   File: _commands.py    (license) View Source Project 5 votes vote down vote up
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 
Example 30
Project: pyomo   Author: Pyomo   File: pyomo_parser.py    (license) View Source Project 5 votes vote down vote up
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() 
Example 31
Project: vspk-python   Author: nuagenetworks   File: cli.py    (license) View Source Project 5 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
        parser.print_help()

        subparsers_actions = [
            action for action in parser._actions
            if isinstance(action, argparse._SubParsersAction)]

        for subparsers_action in subparsers_actions:

            for choice, subparser in subparsers_action.choices.items():
                print("\n{}:\n{}".format(choice.upper(), "-" * (len(choice) + 1)))
                print(subparser.format_help())

        parser.exit() 
Example 32
Project: downloader_cluster   Author: ShichaoMa   File: downloader.py    (license) View Source Project 5 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
        parser.print_help()
        subparsers_actions = [
            action for action in parser._actions
            if isinstance(action, _SubParsersAction)]
        for subparsers_action in subparsers_actions:
            for choice, subparser in subparsers_action.choices.items():
                print("Command '{}'".format(choice))
                print(subparser.format_usage())

        parser.exit() 
Example 33
Project: conda-shell   Author: gbrener   File: conda_cli.py    (license) View Source Project 5 votes vote down vote up
def __init__(self):
        """Constructor."""
        # Extend sys.path so that conda.cli module can be imported, then import
        # conda's CLI modules.
        self.conda_sp_dpath = self._get_conda_sp_dpath()
        self.prefix_dpath = os.path.join(
            os.path.split(os.path.split(os.path.split(
                self.conda_sp_dpath
            )[0])[0])[0],
            'envs',
        )
        (self._base_mod,
         self._main_mod,
         self._main_install_mod,
         self._main_create_mod) = self._import_conda_modules()

        self._create_parser, self._install_parser = None, None
        parser, sub_parsers = self._main_mod.generate_parser()
        self._main_install_mod.configure_parser(sub_parsers)
        self._main_create_mod.configure_parser(sub_parsers)

        subparsers_action = None
        for action in parser._subparsers._actions:
            if isinstance(action, argparse._SubParsersAction):
                subparsers_action = action
                break
        action_parser_map = subparsers_action._name_parser_map
        if 'install' in action_parser_map:
            self._install_parser = action_parser_map['install']
            # These arguments are somehow dropped from the Namespace
            self._install_parser.add_argument('--no-default-packages',
                                              default=False)
            self._install_parser.add_argument('--clone', default=False)
        if 'create' in action_parser_map:
            self._create_parser = action_parser_map['create']
        # Additional branches may be added here to support more of conda's
        # subparsers 
Example 34
Project: zaphod   Author: sanjayankur31   File: zaphod.py    (license) View Source Project 5 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
        """Custom call method."""
        parser.print_help()
        print("\n")

        subparsers_actions = [
            action for action in parser._actions
            if isinstance(action, argparse._SubParsersAction)]
        for subparsers_action in subparsers_actions:
            for choice, subparser in subparsers_action.choices.items():
                print("Subcommand: '{}'".format(choice))
                print(subparser.format_help()) 
Example 35
Project: argparseweb   Author: nirizr   File: page.py    (license) View Source Project 4 votes vote down vote up
def get_input_object(self, action, prefix):
    input_parameters = {}
    input_parameters['class'] = self.get_class(prefix)
    input_parameters['name'] = self.get_id(action, prefix)
    input_parameters['id'] = self.get_id(action, prefix)

    input_type = web.form.Textbox

    if self.get_choices(action):
      input_type = web.form.Dropdown
      input_parameters['args'] = [choice for choice in action.choices]
      if self.get_multiple(action):
        input_parameters['multiple'] = 'multiple'
        input_parameters['size'] = 4
    elif isinstance(action, (argparse._StoreTrueAction, argparse._StoreFalseAction, argparse._StoreConstAction)):
      input_type = web.form.Checkbox
      input_parameters['checked'] = True if action.default else False
      input_parameters['value'] = action.const
    else:
      input_parameters['value'] = action.default if action.default else ""

    if isinstance(action, argparse._SubParsersAction):
      input_parameters['onChange'] = "javascript: update_show(this);"
      input_parameters['value'] = action.choices.keys()[0]

    if len(action.option_strings):
      input_parameters['default'] = action.default
      # if optional argument may be present with either 1 or no parameters, the default shifts
      # to being the no parameter's value. this is mearly to properly display actual values to the user
      if action.nargs == '?':
        input_parameters['value'] = action.const

    # TODO: support these actions: append, append_const, count
    self._actions[self.get_id(action, prefix)] = action
    input_object = input_type(**input_parameters)

    input_object.description = self.get_description(action)
    input_object.nargs = self.get_nargs(action)
    input_object.help = self.get_help(action)
    input_object.disposition = self.get_disposition(action)
    input_object.subparser = self.get_subparser(action)
    input_object.choices = self.get_choices(action)

    return input_object