How to use the cmd2.Cmd2ArgumentParser function in cmd2

To help you get started, we’ve selected a few cmd2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github python-cmd2 / cmd2 / tests / test_argparse_completer.py View on Github external
# Uses default flag prefix value (-)
    flag_parser = Cmd2ArgumentParser()
    flag_parser.add_argument('-n', '--normal_flag', help='a normal flag', action='store_true')
    flag_parser.add_argument('-a', '--append_flag', help='append flag', action='append')
    flag_parser.add_argument('-o', '--append_const_flag', help='append const flag', action='append_const', const=True)
    flag_parser.add_argument('-c', '--count_flag', help='count flag', action='count')
    flag_parser.add_argument('-s', '--suppressed_flag', help=argparse.SUPPRESS, action='store_true')
    flag_parser.add_argument('-r', '--remainder_flag', nargs=argparse.REMAINDER, help='a remainder flag')

    @with_argparser(flag_parser)
    def do_flag(self, args: argparse.Namespace) -> None:
        pass

    # Uses non-default flag prefix value (+)
    plus_flag_parser = Cmd2ArgumentParser(prefix_chars='+')
    plus_flag_parser.add_argument('+n', '++normal_flag', help='a normal flag', action='store_true')

    @with_argparser(plus_flag_parser)
    def do_plus_flag(self, args: argparse.Namespace) -> None:
        pass

    ############################################################################################################
    # Begin code related to testing choices, choices_function, and choices_method parameters
    ############################################################################################################
    def choices_method(self) -> List[str]:
        """Method that provides choices"""
        return choices_from_method

    def completion_item_method(self) -> List[CompletionItem]:
        """Choices method that returns CompletionItems"""
        items = []
github python-cmd2 / cmd2 / tests / test_argparse_custom.py View on Github external
def test_apcustom_usage():
    usage = "A custom usage statement"
    parser = Cmd2ArgumentParser(usage=usage)
    assert usage in parser.format_help()
github python-cmd2 / cmd2 / tests / test_argparse_custom.py View on Github external
def test_apcustom_no_choices_callables_when_nargs_is_0(kwargs):
    with pytest.raises(TypeError) as excinfo:
        parser = Cmd2ArgumentParser()
        parser.add_argument('name', action='store_true', **kwargs)
    assert 'None of the following parameters can be used on an action that takes no arguments' in str(excinfo.value)
github python-cmd2 / cmd2 / tests / test_argparse_completer.py View on Github external
choices_function=choices_function)
    choices_parser.add_argument("method_pos", help="a positional populated with a choices method",
                                choices_method=choices_method)

    @with_argparser(choices_parser)
    def do_choices(self, args: argparse.Namespace) -> None:
        pass

    ############################################################################################################
    # Begin code related to testing completer_function and completer_method parameters
    ############################################################################################################
    def completer_method(self, text: str, line: str, begidx: int, endidx: int) -> List[str]:
        """Tab completion method"""
        return basic_complete(text, line, begidx, endidx, completions_from_method)

    completer_parser = Cmd2ArgumentParser()

    # Flag args for completer command
    completer_parser.add_argument("-f", "--function", help="a flag using a completer function",
                                  completer_function=completer_function)
    completer_parser.add_argument("-m", "--method", help="a flag using a completer method",
                                  completer_method=completer_method)

    # Positional args for completer command
    completer_parser.add_argument("function_pos", help="a positional using a completer function",
                                  completer_function=completer_function)
    completer_parser.add_argument("method_pos", help="a positional using a completer method",
                                  completer_method=completer_method)

    @with_argparser(completer_parser)
    def do_completer(self, args: argparse.Namespace) -> None:
        pass
github python-cmd2 / cmd2 / tests / test_argparse_completer.py View on Github external
def test_complete_command_help_no_tokens(ac_app):
    from cmd2.argparse_completer import AutoCompleter

    parser = Cmd2ArgumentParser()
    ac = AutoCompleter(parser, ac_app)

    completions = ac.complete_subcommand_help(tokens=[], text='', line='', begidx=0, endidx=0)
    assert not completions
github python-cmd2 / cmd2 / tests / test_argparse_completer.py View on Github external
def test_looks_like_flag():
    from cmd2.argparse_completer import _looks_like_flag
    parser = Cmd2ArgumentParser()

    # Does not start like a flag
    assert not _looks_like_flag('', parser)
    assert not _looks_like_flag('non-flag', parser)
    assert not _looks_like_flag('-', parser)
    assert not _looks_like_flag('--has space', parser)
    assert not _looks_like_flag('-2', parser)

    # Does start like a flag
    assert _looks_like_flag('--', parser)
    assert _looks_like_flag('-flag', parser)
    assert _looks_like_flag('--flag', parser)
github python-cmd2 / cmd2 / tests / test_argparse_completer.py View on Github external
def test_single_prefix_char():
    from cmd2.argparse_completer import _single_prefix_char
    parser = Cmd2ArgumentParser(prefix_chars='-+')

    # Invalid
    assert not _single_prefix_char('', parser)
    assert not _single_prefix_char('--', parser)
    assert not _single_prefix_char('-+', parser)
    assert not _single_prefix_char('++has space', parser)
    assert not _single_prefix_char('foo', parser)

    # Valid
    assert _single_prefix_char('-', parser)
    assert _single_prefix_char('+', parser)
github python-cmd2 / cmd2 / examples / custom_parser.py View on Github external
# coding=utf-8
"""
Defines the CustomParser used with override_parser.py example
"""
import sys

from cmd2 import Cmd2ArgumentParser, set_default_argument_parser
from cmd2 import ansi


# First define the parser
class CustomParser(Cmd2ArgumentParser):
    """Overrides error class"""
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

    def error(self, message: str) -> None:
        """Custom override that applies custom formatting to the error message"""
        lines = message.split('\n')
        linum = 0
        formatted_message = ''
        for line in lines:
            if linum == 0:
                formatted_message = 'Error: ' + line
            else:
                formatted_message += '\n       ' + line
            linum += 1
github HynekPetrak / sshame / sshame / main.py View on Github external
continue
            self.db.commit()
        if arg.enable:
            ips = [ipaddress.ip_network(x, False) for x in arg.enable]
            hosts = self.db.query(Host)
            for h in hosts:
                a = ipaddress.ip_address(h.address)
                for n in ips:
                    if (a in n):
                        h.enabled = True
                        continue
            self.db.commit()

    complete_hosts = cmd2.Cmd.path_complete

    keys_parser = cmd2.Cmd2ArgumentParser()
    keys_item_group = keys_parser.add_mutually_exclusive_group()
    keys_item_group.add_argument(
        '-a', '--add', type=str, nargs='+', help='Add keys')
    keys_item_group.add_argument(
        '-l', '--list', action='store_true', help='List keys')
    keys_item_group.add_argument(
        '-d', '--disable', type=str, nargs='+', help='Disable keys')
    keys_parser.add_argument('-p', '--passwd', type=str, nargs='*',
                             help='List of password to use for encrypted private keys')

    @cmd2.with_argparser(keys_parser)
    @cmd2.with_category(CMD_CAT_SSHAME)
    def do_keys(self, arg):
        'Maintain the private keys'
        def load_private_key(f, pwd):
            try:
github python-cmd2 / cmd2 / examples / table_display.py View on Github external
def make_table_parser() -> Cmd2ArgumentParser:
    """Create a unique instance of an argparse Argument parser for processing table arguments.

    NOTE: The two cmd2 argparse decorators require that each parser be unique, even if they are essentially a deep copy
    of each other.  For cases like that, you can create a function to return a unique instance of a parser, which is
    what is being done here.
    """
    table_parser = Cmd2ArgumentParser()
    table_item_group = table_parser.add_mutually_exclusive_group()
    table_item_group.add_argument('-c', '--color', action='store_true', help='Enable color')
    table_item_group.add_argument('-f', '--fancy', action='store_true', help='Fancy Grid')
    table_item_group.add_argument('-s', '--sparse', action='store_true', help='Sparse Grid')
    return table_parser