Python argparse._SubParsersAction() Examples

The following are 30 code examples of argparse._SubParsersAction(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module argparse , or try the search function .
Example #1
Source File: cli.py    From spectacles with MIT License 6 votes vote down vote up
def _build_connect_subparser(
    subparser_action: argparse._SubParsersAction,
    base_subparser: argparse.ArgumentParser,
) -> None:
    """Returns the subparser for the subcommand `connect`.

    Args:
        subparser_action (type): Description of parameter `subparser_action`.
        base_subparser (type): Description of parameter `base_subparser`.

    Returns:
        type: Description of returned object.

    """
    subparser_action.add_parser(
        "connect",
        parents=[base_subparser],
        help="Connect to Looker instance to test credentials.",
    ) 
Example #2
Source File: report.py    From allentune with Apache License 2.0 6 votes vote down vote up
def add_subparser(self, name: str, parser: argparse._SubParsersAction) -> argparse.ArgumentParser:
        subparser = parser.add_parser(
                name, description="generate report from experiment", help='Generate a report from hyperparameter search experiments.')
        subparser.add_argument(
            "--log-dir",
            required=True,
        )
        subparser.add_argument(
            '--performance-metric',
            required=False,
            type=str
        )
        subparser.add_argument(
            '--model',
            required=False,
            type=str
        )
        subparser.set_defaults(func=generate_report)

        return subparser 
Example #3
Source File: __init__.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def parse_args(self, args=None, namespace=None):
        namespace = super(QubesArgumentParser, self).parse_args(args, namespace)

        if self._want_app and not self._want_app_no_instance:
            self.set_qubes_verbosity(namespace)
            namespace.app = qubes.Qubes(namespace.app,
                offline_mode=namespace.offline_mode)

        if self._want_force_root:
            self.dont_run_as_root(namespace)

        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
                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 #4
Source File: command_domain.py    From cf-python-client with Apache License 2.0 6 votes vote down vote up
def list(self) -> Command:
        entry = self._list_entry()

        def execute(client: CloudFoundryClient, arguments: Namespace):
            filter_list = dict()
            for filter_parameter in self.filter_list_parameters:
                filter_value = getattr(arguments, filter_parameter)
                if filter_value is not None:
                    filter_list[filter_parameter] = filter_value
            for entity in self._get_client_domain(client).list(**filter_list):
                if self.name_property is not None:
                    print('%s - %s' % (self.id(entity), self.name(entity)))
                else:
                    print(self.id(entity))

        def generate_parser(parser: _SubParsersAction):
            list_parser = parser.add_parser(entry)
            for filter_parameter in self.filter_list_parameters:
                list_parser.add_argument('-%s' % filter_parameter, action='store', dest=filter_parameter, type=str,
                                         default=None, help='Filter with %s' % filter_parameter)

        return Command(entry, generate_parser, execute) 
Example #5
Source File: command_domain.py    From cf-python-client with Apache License 2.0 6 votes vote down vote up
def delete(self) -> Command:
        entry = self._delete_entry()

        def execute(client: CloudFoundryClient, arguments: Namespace):
            if self.is_guid(arguments.id[0]):
                self._get_client_domain(client)._remove(arguments.id[0])
            elif self.allow_retrieve_by_name:
                entity = self.find_by_name(client, arguments.id[0])
                if entity is None:
                    raise InvalidStatusCode(HTTPStatus.NOT_FOUND,
                                            '%s with name %s' % (self.client_domain, arguments.id[0]))
                else:
                    self._get_client_domain(client)._remove(self.id(entity))
            else:
                raise ValueError('id: %s: does not allow search by name' % self.client_domain)

        def generate_parser(parser: _SubParsersAction):
            delete_parser = parser.add_parser(entry)
            delete_parser.add_argument('id', metavar='ids', type=str, nargs=1,
                                       help='The id. Can be UUID or name (first found then)'
                                       if self.allow_retrieve_by_name else 'The id (UUID)')

        return Command(entry, generate_parser, execute) 
Example #6
Source File: cli.py    From spectacles with MIT License 6 votes vote down vote up
def _build_content_subparser(
    subparser_action: argparse._SubParsersAction,
    base_subparser: argparse.ArgumentParser,
) -> None:
    subparser = subparser_action.add_parser(
        "content", parents=[base_subparser], help="Run Looker content validation."
    )

    subparser.add_argument(
        "--incremental",
        action="store_true",
        help="Only display errors which are not present on the master branch.",
    )

    subparser.add_argument(
        "--exclude-personal",
        action="store_true",
        help="Exclude errors found in content in personal folders.",
    )

    _build_validator_subparser(subparser_action, subparser) 
Example #7
Source File: cli.py    From spectacles with MIT License 6 votes vote down vote up
def _build_assert_subparser(
    subparser_action: argparse._SubParsersAction,
    base_subparser: argparse.ArgumentParser,
) -> None:
    """Returns the subparser for the subcommand `assert`.

    Args:
        subparser_action: Description of parameter `subparser_action`.
        base_subparser: Description of parameter `base_subparser`.

    Returns:
        type: Description of returned object.

    """
    subparser = subparser_action.add_parser(
        "assert", parents=[base_subparser], help="Run Looker data tests."
    )

    _build_validator_subparser(subparser_action, subparser) 
Example #8
Source File: __init__.py    From scif with Mozilla Public License 2.0 6 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 #9
Source File: save_help_text.py    From cmd2 with MIT License 6 votes vote down vote up
def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]:
    """Get a list of subcommands for an ArgumentParser"""
    sub_cmds = []

    # Check if this is parser has subcommands
    if parser is not None and parser._subparsers is not None:

        # Find the _SubParsersAction for the subcommands of this parser
        for action in parser._subparsers._actions:
            if isinstance(action, argparse._SubParsersAction):
                for sub_cmd, sub_cmd_parser in action.choices.items():
                    sub_cmds.append(sub_cmd)

                    # Look for nested subcommands
                    for nested_sub_cmd in get_sub_commands(sub_cmd_parser):
                        sub_cmds.append('{} {}'.format(sub_cmd, nested_sub_cmd))

                break

    sub_cmds.sort()
    return sub_cmds 
Example #10
Source File: commands.py    From Uwallet with MIT License 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 #11
Source File: show.py    From rasa_core with Apache License 2.0 6 votes vote down vote up
def add_subparser(subparsers: argparse._SubParsersAction,
                  parents: List[argparse.ArgumentParser]):
    show_parser = subparsers.add_parser(
        "show",
        parents=parents,
        conflict_handler="resolve",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        help="Visualize Rasa Stack data")

    show_subparsers = show_parser.add_subparsers()
    show_stories_subparser = show_subparsers.add_parser(
        "stories",
        conflict_handler='resolve',
        parents=parents,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        help="Show Rasa Core stories")

    add_core_visualization_params(show_stories_subparser)
    add_config_param(show_stories_subparser)
    show_stories_subparser.set_defaults(func=show_stories)

    show_parser.set_defaults(func=lambda _: show_parser.print_help(None)) 
Example #12
Source File: utils.py    From rasa_core with Apache License 2.0 6 votes vote down vote up
def set_default_subparser(parser,
                          default_subparser):
    """default subparser selection. Call after setup, just before parse_args()

    parser: the name of the parser you're making changes to
    default_subparser: the name of the subparser to call by default"""
    subparser_found = False
    for arg in sys.argv[1:]:
        if arg in ['-h', '--help']:  # global help if no subparser
            break
    else:
        for x in parser._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 before all other arguments
            sys.argv.insert(1, default_subparser) 
Example #13
Source File: main.py    From bandersnatch with Academic Free License v3.0 6 votes vote down vote up
def _delete_parser(subparsers: argparse._SubParsersAction) -> None:
    d = subparsers.add_parser(
        "delete",
        help=(
            "Consulte metadata (locally or remotely) and delete "
            + "entire pacakge artifacts."
        ),
    )
    d.add_argument(
        "--dry-run",
        action="store_true",
        default=False,
        help="Do not download or delete files",
    )
    d.add_argument(
        "--workers",
        type=int,
        default=0,
        help="# of parallel iops [Defaults to bandersnatch.conf]",
    )
    d.add_argument("pypi_packages", nargs="*")
    d.set_defaults(op="delete") 
Example #14
Source File: cli.py    From apm-integration-testing with Apache License 2.0 6 votes vote down vote up
def store_options(self, parser):
        """
        Helper method to extract and store all arguments
        in a list of all possible arguments.
        Used for bash tab completion.
        """
        # Run through all parser actions
        for action in parser._actions:
            for option in action.option_strings:
                self.available_options.add(option)

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

        # Run through all subparser actions
        for subparsers_action in subparsers_actions:
            for choice, subparser in subparsers_action.choices.items():
                self.available_options.add(choice)

    #
    # handlers
    # 
Example #15
Source File: base.py    From trains-agent with Apache License 2.0 6 votes vote down vote up
def _parse_known_args(self, arg_strings, *args, **kwargs):
        in_args = set(arg_strings)
        d_sp = self.__default_subparser
        if d_sp is not None and not {'-h', '--help'}.intersection(in_args):
            for x in self._subparsers._actions:
                subparser_found = (
                        isinstance(x, argparse._SubParsersAction) and
                        in_args.intersection(x._name_parser_map.keys())
                )
                if subparser_found:
                    break
            else:
                # insert default in first position, this implies no
                # global options without a sub_parsers specified
                arg_strings = [d_sp] + arg_strings
        return super(Parser, self)._parse_known_args(
            arg_strings, *args, **kwargs
        ) 
Example #16
Source File: __init__.py    From nixpkgs-review with MIT License 6 votes vote down vote up
def wip_flags(subparsers: argparse._SubParsersAction) -> argparse.ArgumentParser:
    wip_parser = subparsers.add_parser(
        "wip", help="review the uncommited changes in the working tree"
    )

    wip_parser.add_argument(
        "-b", "--branch", default="master", help="branch to compare against with"
    )
    wip_parser.add_argument(
        "-s",
        "--staged",
        action="store_true",
        default=False,
        help="Whether to build staged changes",
    )
    wip_parser.add_argument(
        "-r",
        "--remote",
        default="https://github.com/NixOS/nixpkgs",
        help="Name of the nixpkgs repo to review",
    )

    wip_parser.set_defaults(func=wip_command)

    return wip_parser 
Example #17
Source File: __init__.py    From nixpkgs-review with MIT License 6 votes vote down vote up
def rev_flags(subparsers: argparse._SubParsersAction) -> argparse.ArgumentParser:
    rev_parser = subparsers.add_parser(
        "rev", help="review a change in the local pull request repository"
    )
    rev_parser.add_argument(
        "-b", "--branch", default="master", help="branch to compare against with"
    )
    rev_parser.add_argument(
        "commit", help="commit/tag/ref/branch in your local git repository"
    )
    rev_parser.add_argument(
        "-r",
        "--remote",
        default="https://github.com/NixOS/nixpkgs",
        help="Name of the nixpkgs repo to review",
    )
    rev_parser.set_defaults(func=rev_command)
    return rev_parser 
Example #18
Source File: query_db.py    From detectron2 with Apache License 2.0 5 votes vote down vote up
def add_parser(cls: type, subparsers: argparse._SubParsersAction):
        parser = subparsers.add_parser(cls.COMMAND, help="Visualize selected entries")
        cls.add_arguments(parser)
        parser.set_defaults(func=cls.execute) 
Example #19
Source File: operation_commands.py    From cf-python-client with Apache License 2.0 5 votes vote down vote up
def generate_push_command() -> Tuple[Command, str]:
    entry = 'push_app'

    def generate_parser(parser: _SubParsersAction):
        command_parser = parser.add_parser(entry)
        command_parser.add_argument('manifest_path', metavar='manifest_paths', type=str, nargs=1,
                                    help='The manifest path')
        command_parser.add_argument('-space_guid', action='store', dest='space_guid', type=str,
                                    help='Space guid')

    def execute(client: CloudFoundryClient, arguments: Namespace):
        manifest_path = arguments.manifest_path[0]
        PushOperation(client).push(arguments.space_guid, manifest_path)

    return Command(entry, generate_parser, execute), 'Push an application by its manifest' 
Example #20
Source File: main.py    From bandersnatch with Academic Free License v3.0 5 votes vote down vote up
def _mirror_parser(subparsers: argparse._SubParsersAction) -> None:
    m = subparsers.add_parser(
        "mirror",
        help="Performs a one-time synchronization with the PyPI master server.",
    )
    m.add_argument(
        "--force-check",
        action="store_true",
        default=False,
        help=(
            "Force bandersnatch to reset the PyPI serial (move serial file to /tmp) to "
            + "perform a full sync"
        ),
    )
    m.set_defaults(op="mirror") 
Example #21
Source File: apps_command_domain.py    From cf-python-client with Apache License 2.0 5 votes vote down vote up
def restart_instance(self) -> Command:
        def generate_parser(parser: _SubParsersAction):
            command_parser = parser.add_parser('restart_instance')
            command_parser.add_argument('id', metavar='ids', type=str, nargs=1,
                                        help='The id. Can be UUID or name (first found then)')
            command_parser.add_argument('instance_id', metavar='instance_ids', type=int, nargs=1,
                                        help='The instance id')

        def execute(client: CloudFoundryClient, arguments: Namespace):
            app_domain = self._get_client_domain(client)
            resource_id = self.resolve_id(arguments.id[0], lambda x: app_domain.get_first(name=x))
            getattr(app_domain, 'restart_instance')(resource_id, int(arguments.instance_id[0]))

        return  Command('restart_instance', generate_parser, execute) 
Example #22
Source File: createdb_parser.py    From pyani with MIT License 5 votes vote down vote up
def build(
    subps: _SubParsersAction, parents: Optional[List[ArgumentParser]] = None
) -> None:
    """Return a command-line parser for the createdb subcommand.

    :param subps:  collection of subparsers in main parser
    :param parents:  parsers from which arguments are inherited

    """
    parser = subps.add_parser(
        "createdb", parents=parents, formatter_class=ArgumentDefaultsHelpFormatter
    )
    # Path to database (default: .pyani/pyanidb)
    parser.add_argument(
        "--dbpath",
        action="store",
        dest="dbpath",
        default=Path(".pyani/pyanidb"),
        type=Path,
        help="path to pyani database",
    )
    parser.add_argument(
        "-f",
        "--force",
        action="store_true",
        dest="force",
        default=False,
        help="force creation of new empty database",
    )
    parser.set_defaults(func=subcommands.subcmd_createdb) 
Example #23
Source File: predict.py    From gtos with MIT License 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', required=True, type=str, help='the archived model to make predictions with')
        subparser.add_argument('--input-file', type=str, help='path to input file')

        subparser.add_argument('--output-file', type=str, help='path to output file')
        subparser.add_argument('--weights-file',
                               type=str,
                               help='a path that overrides which weights file to use')

        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')

        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)')

        subparser.add_argument('--use-dataset-reader',
                               action='store_true',
                               help='Whether to use the dataset reader of the original model to load Instances')

        subparser.add_argument('-o', '--overrides',
                               type=str,
                               default="",
                               help='a JSON structure used to override the experiment configuration')

        subparser.set_defaults(func=_predict)

        return subparser 
Example #24
Source File: subcommand.py    From gtos with MIT License 5 votes vote down vote up
def add_subparser(self, name: str, parser: argparse._SubParsersAction) -> argparse.ArgumentParser:
        # pylint: disable=protected-access
        raise NotImplementedError 
Example #25
Source File: utils.py    From gpuview with MIT License 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("Subparser '{}'".format(choice))
                print(subparser.format_help())
        parser.exit() 
Example #26
Source File: argparsers.py    From weevely3 with GNU General Public License v3.0 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
Source File: cli.py    From lbry-sdk with MIT License 5 votes vote down vote up
def _granular_action_groups(self):
        if self.prog != 'lbrynet':
            yield from self._action_groups
            return
        yield self._optionals
        action: argparse._SubParsersAction = self._positionals._group_actions[0]
        yield split_subparser_argument(
            self, action, "Grouped Commands", lambda parser: 'group' in parser._defaults
        )
        yield split_subparser_argument(
            self, action, "Commands", lambda parser: 'group' not in parser._defaults
        ) 
Example #28
Source File: cli.py    From lbry-sdk with MIT License 5 votes vote down vote up
def split_subparser_argument(parent, original, name, condition):
    new_sub_parser = argparse._SubParsersAction(
        original.option_strings,
        original._prog_prefix,
        original._parser_class,
        metavar=original.metavar
    )
    new_sub_parser._name_parser_map = original._name_parser_map
    new_sub_parser._choices_actions = [
        a for a in original._choices_actions if condition(original._name_parser_map[a.dest])
    ]
    group = argparse._ArgumentGroup(parent, name)
    group._group_actions = [new_sub_parser]
    return group 
Example #29
Source File: cli.py    From spectacles with MIT License 5 votes vote down vote up
def _build_sql_subparser(
    subparser_action: argparse._SubParsersAction,
    base_subparser: argparse.ArgumentParser,
) -> None:
    """Returns the subparser for the subcommand `sql`.

    Args:
        subparser_action: Description of parameter `subparser_action`.
        base_subparser: Description of parameter `base_subparser`.

    Returns:
        type: Description of returned object.

    """
    subparser = subparser_action.add_parser(
        "sql",
        parents=[base_subparser],
        help="Build and run queries to test your Looker instance.",
    )

    _build_validator_subparser(subparser_action, subparser)

    subparser.add_argument(
        "--mode",
        choices=["batch", "single", "hybrid"],
        default="batch",
        help="Specify the mode the SQL validator should run.\
            In single-dimension mode, the SQL validator will run one query \
            per dimension. In batch mode, the SQL validator will create one \
            query per explore. In hybrid mode, the SQL validator will run in \
            batch mode and then run errored explores in single-dimension mode.",
    )
    subparser.add_argument(
        "--concurrency",
        default=10,
        type=int,
        help="Specify how many concurrent queries you want to have running \
            against your data warehouse. The default is 10.",
    ) 
Example #30
Source File: utils.py    From MMNet with Apache License 2.0 5 votes vote down vote up
def get_subparser_argument_list(parser, subparser_name):
    # Hack argparse and get subparser's arguments
    from argparse import _SubParsersAction
    argument_list = []
    for sub_parser_action in filter(lambda x: isinstance(x, _SubParsersAction), parser._subparsers._actions):
        for action in sub_parser_action.choices[subparser_name]._actions:
            arg = action.option_strings[-1].replace("--", "")
            if arg == "help":
                continue
            if arg.startswith("no-"):
                continue
            argument_list.append(arg)
    return argument_list