Python argparse._SubParsersAction() Examples

The following are 30 code examples for showing how to use argparse._SubParsersAction(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module argparse , or try the search function .

Example 1
Project: spectacles   Author: spectacles-ci   File: cli.py    License: 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
Project: spectacles   Author: spectacles-ci   File: cli.py    License: 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 3
Project: spectacles   Author: spectacles-ci   File: cli.py    License: 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 4
Project: allentune   Author: allenai   File: report.py    License: 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 5
Project: qubes-core-admin   Author: QubesOS   File: __init__.py    License: 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 6
Project: rasa_core   Author: RasaHQ   File: show.py    License: 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 7
Project: rasa_core   Author: RasaHQ   File: utils.py    License: 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 8
Project: apm-integration-testing   Author: elastic   File: cli.py    License: 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 9
Project: trains-agent   Author: allegroai   File: base.py    License: 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 10
Project: nixpkgs-review   Author: Mic92   File: __init__.py    License: 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 11
Project: nixpkgs-review   Author: Mic92   File: __init__.py    License: 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 12
Project: bandersnatch   Author: pypa   File: main.py    License: 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 13
Project: Uwallet   Author: UlordChain   File: commands.py    License: 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 14
Project: cmd2   Author: python-cmd2   File: save_help_text.py    License: 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 15
Project: scif   Author: vsoch   File: __init__.py    License: 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 16
Project: cf-python-client   Author: cloudfoundry-community   File: command_domain.py    License: 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 17
Project: cf-python-client   Author: cloudfoundry-community   File: command_domain.py    License: 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 18
Project: spectacles   Author: spectacles-ci   File: cli.py    License: 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 19
Project: allentune   Author: allenai   File: subcommand.py    License: Apache License 2.0 5 votes vote down vote up
def add_subparser(self, name: str, parser: argparse._SubParsersAction) -> argparse.ArgumentParser:
        # pylint: disable=protected-access
        raise NotImplementedError 
Example 20
Project: scrapy-cluster   Author: istresearch   File: argparse_helper.py    License: MIT License 5 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
        parser.print_help()
        print()

        subparsers_actions = [
            action for action in parser._actions
            if isinstance(action, argparse._SubParsersAction)]
        for subparsers_action in subparsers_actions:
            for choice, subparser in list(subparsers_action.choices.items()):
                print("Command '{}'".format(choice))
                print(subparser.format_usage())

        parser.exit() 
Example 21
Project: airflow   Author: apache   File: cli_parser.py    License: Apache License 2.0 5 votes vote down vote up
def _format_action(self, action: Action):
        if isinstance(action, argparse._SubParsersAction):  # pylint: disable=protected-access

            parts = []
            action_header = self._format_action_invocation(action)
            action_header = '%*s%s\n' % (self._current_indent, '', action_header)
            parts.append(action_header)

            self._indent()
            subactions = action._get_subactions()  # pylint: disable=protected-access
            action_subcommnads, group_subcommnands = partition(
                lambda d: isinstance(ALL_COMMANDS_DICT[d.dest], GroupCommand), subactions
            )
            parts.append("\n")
            parts.append('%*s%s:\n' % (self._current_indent, '', "Groups"))
            self._indent()
            for subaction in group_subcommnands:
                parts.append(self._format_action(subaction))
            self._dedent()

            parts.append("\n")
            parts.append('%*s%s:\n' % (self._current_indent, '', "Commands"))
            self._indent()

            for subaction in action_subcommnads:
                parts.append(self._format_action(subaction))
            self._dedent()
            self._dedent()

            # return a single string
            return self._join_parts(parts)

        return super()._format_action(action) 
Example 22
Project: airflow   Author: apache   File: cli_parser.py    License: Apache License 2.0 5 votes vote down vote up
def _add_command(
    subparsers: argparse._SubParsersAction,  # pylint: disable=protected-access
    sub: CLICommand
) -> None:
    sub_proc = subparsers.add_parser(
        sub.name, help=sub.help, description=sub.description or sub.help,
    )
    sub_proc.formatter_class = RawTextHelpFormatter

    if isinstance(sub, GroupCommand):
        _add_group_command(sub, sub_proc)
    elif isinstance(sub, ActionCommand):
        _add_action_command(sub, sub_proc)
    else:
        raise AirflowException("Invalid command definition.") 
Example 23
Project: OpenBookQA   Author: allenai   File: evaluate_predictions_qa_mc_know_visualize.py    License: Apache License 2.0 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 with optional output'''
        subparser = parser.add_parser('evaluate_predictions_qa_mc_know_visualize',
                                      description=description,
                                      help='Evaluate the specified model + dataset with optional output')
        subparser.add_argument('--archive_file',
                               type=str,
                               required=True,
                               help='path to an archived trained model')
        subparser.add_argument('--evaluation_data_file',
                               type=str,
                               required=False,
                               help='path to the file containing the evaluation data. This can be list of files splitted with ";". If no evaluation file is specified it searches for validation_data_file and test_data_file in the model config')
        subparser.add_argument('--output_file',
                               type=str,
                               required=False,
                               help='output file for raw evaluation results. This can be list of files splitted with ";". At least one value is required that is used as prefix for the output of the results from the evaluation files when evaluation_data_file is not specified! ')
        subparser.add_argument('--cuda_device',
                               type=int,
                               default=-1,
                               help='id of GPU to use (if any)')
        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 24
Project: OpenBookQA   Author: allenai   File: evaluate_custom.py    License: Apache License 2.0 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 with optional output'''
        subparser = parser.add_parser('evaluate_custom',
                                      description=description,
                                      help='Evaluate the specified model + dataset with optional output')
        subparser.add_argument('--archive_file',
                               type=str,
                               required=True,
                               help='path to an archived trained model')
        subparser.add_argument('--evaluation_data_file',
                               type=str,
                               required=True,
                               help='path to the file containing the evaluation data')
        subparser.add_argument('--output_file',
                               type=str,
                               required=False,
                               help='output file for raw evaluation results')
        subparser.add_argument('--cuda_device',
                               type=int,
                               default=-1,
                               help='id of GPU to use (if any)')
        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 25
Project: OpenBookQA   Author: allenai   File: evaluate_predictions_qa_mc.py    License: Apache License 2.0 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 with optional output'''
        subparser = parser.add_parser('evaluate_predictions_qa_mc',
                                      description=description,
                                      help='Evaluate the specified model + dataset with optional output')
        subparser.add_argument('--archive_file',
                               type=str,
                               required=True,
                               help='path to an archived trained model')
        subparser.add_argument('--evaluation_data_file',
                               type=str,
                               required=False,
                               help='path to the file containing the evaluation data. This can be list of files splitted with ";". If no evaluation file is specified it searches for validation_data_file and test_data_file in the model config')
        subparser.add_argument('--output_file',
                               type=str,
                               required=False,
                               help='output file for raw evaluation results. This can be list of files splitted with ";". At least one value is required that is used as prefix for the output of the results from the evaluation files when evaluation_data_file is not specified! ')
        subparser.add_argument('--cuda_device',
                               type=int,
                               default=-1,
                               help='id of GPU to use (if any)')
        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 26
Project: WebPocket   Author: TuuuNya   File: pyscript_bridge.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __dir__(self):
        """Returns a custom list of attribute names to match the sub-commands"""
        commands = []
        for action in self.__current_subcommand_parser._actions:
            if not action.option_strings and isinstance(action, argparse._SubParsersAction):
                commands.extend(action.choices)
        return commands 
Example 27
Project: WebPocket   Author: TuuuNya   File: pyscript_bridge.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __getattr__(self, item: str):
        """Search for a sub-command matching this item and update internal state to track the traversal"""
        # look for sub-command under the current command/sub-command layer
        for action in self.__current_subcommand_parser._actions:
            if not action.option_strings and isinstance(action, argparse._SubParsersAction):
                if item in action.choices:
                    # item matches the a sub-command, save our position in argparse,
                    # save the sub-command, return self to allow next level of traversal
                    self.__current_subcommand_parser = action.choices[item]
                    self._args[action.dest] = item
                    return self

        raise AttributeError(item) 
Example 28
Project: pydatalab   Author: googledatalab   File: _commands.py    License: Apache License 2.0 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 29
Project: allennlp   Author: allenai   File: subcommand.py    License: Apache License 2.0 5 votes vote down vote up
def add_subparser(self, parser: argparse._SubParsersAction) -> argparse.ArgumentParser:
        raise NotImplementedError 
Example 30
Project: allennlp   Author: allenai   File: print_results.py    License: Apache License 2.0 5 votes vote down vote up
def add_subparser(self, parser: argparse._SubParsersAction) -> argparse.ArgumentParser:

        description = """Print results from allennlp training runs in a helpful CSV format."""
        subparser = parser.add_parser(
            self.name,
            description=description,
            help="Print results from allennlp serialization directories to the console.",
        )
        subparser.add_argument(
            "path",
            type=str,
            help="Path to recursively search for allennlp serialization directories.",
        )

        subparser.add_argument(
            "-k",
            "--keys",
            type=str,
            nargs="+",
            help="Keys to print from metrics.json."
            'Keys not present in all metrics.json will result in "N/A"',
            default=None,
            required=False,
        )
        subparser.add_argument(
            "-m",
            "--metrics-filename",
            type=str,
            help="Name of the metrics file to inspect.",
            default="metrics.json",
            required=False,
        )

        subparser.set_defaults(func=print_results_from_args)
        return subparser