How to use the cmd2.Cmd 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_cmd2.py View on Github external
@pytest.fixture
def helpcat_app():
    app = HelpCategoriesApp()
    return app

def test_help_cat_base(helpcat_app):
    out, err = run_cmd(helpcat_app, 'help')
    verify_help_text(helpcat_app, out)

def test_help_cat_verbose(helpcat_app):
    out, err = run_cmd(helpcat_app, 'help --verbose')
    verify_help_text(helpcat_app, out)


class SelectApp(cmd2.Cmd):
    def do_eat(self, arg):
        """Eat something, with a selection of sauces to choose from."""
        # Pass in a single string of space-separated selections
        sauce = self.select('sweet salty', 'Sauce? ')
        result = '{food} with {sauce} sauce, yum!'
        result = result.format(food=arg, sauce=sauce)
        self.stdout.write(result + '\n')

    def do_study(self, arg):
        """Learn something, with a selection of subjects to choose from."""
        # Pass in a list of strings for selections
        subject = self.select(['math', 'science'], 'Subject? ')
        result = 'Good luck learning {}!\n'.format(subject)
        self.stdout.write(result)

    def do_procrastinate(self, arg):
github python-cmd2 / cmd2 / tests / test_argparse.py View on Github external
from .conftest import run_cmd

# Prefer statically linked gnureadline if available (for macOS compatibility due to issues with libedit)
try:
    import gnureadline as readline
except ImportError:
    # Try to import readline, but allow failure for convenience in Windows unit testing
    # Note: If this actually fails, you should install readline on Linux or Mac or pyreadline on Windows
    try:
        # noinspection PyUnresolvedReferences
        import readline
    except ImportError:
        pass


class ArgparseApp(cmd2.Cmd):
    def __init__(self):
        self.maxrepeats = 3
        cmd2.Cmd.__init__(self)

    def namespace_provider(self) -> argparse.Namespace:
        ns = argparse.Namespace()
        ns.custom_stuff = "custom"
        return ns

    say_parser = argparse.ArgumentParser()
    say_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
    say_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
    say_parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
    say_parser.add_argument('words', nargs='+', help='words to say')

    @cmd2.with_argparser(say_parser)
github python-cmd2 / cmd2 / tests / test_cmd2.py View on Github external
def CreateOutsimApp():
    c = cmd2.Cmd()
    c.stdout = utils.StdSim(c.stdout)
    return c
github python-cmd2 / cmd2 / tests / test_history.py View on Github external
def test_history_file_permission_error(mocker, capsys):
    mock_open = mocker.patch('builtins.open')
    mock_open.side_effect = PermissionError

    cmd2.Cmd(persistent_history_file='/tmp/doesntmatter')
    out, err = capsys.readouterr()
    assert not out
    assert 'Can not read' in err
github python-cmd2 / cmd2 / tests / test_argparse_completer.py View on Github external
def choices_takes_arg_tokens(arg_tokens: argparse.Namespace) -> List[str]:
    """Choices function that receives arg_tokens from AutoCompleter"""
    return [arg_tokens['parent_arg'][0], arg_tokens['subcommand'][0]]


def completer_takes_arg_tokens(text: str, line: str, begidx: int, endidx: int,
                               arg_tokens: argparse.Namespace) -> List[str]:
    """Completer function that receives arg_tokens from AutoCompleter"""
    match_against = [arg_tokens['parent_arg'][0], arg_tokens['subcommand'][0]]
    return basic_complete(text, line, begidx, endidx, match_against)


# noinspection PyMethodMayBeStatic,PyUnusedLocal
class AutoCompleteTester(cmd2.Cmd):
    """Cmd2 app that exercises AutoCompleter class"""
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    ############################################################################################################
    # Begin code related to help and command name completion
    ############################################################################################################
    # Top level parser for music command
    music_parser = Cmd2ArgumentParser(description='Manage music')

    # Add subcommands to music
    music_subparsers = music_parser.add_subparsers()
    music_create_parser = music_subparsers.add_parser('create', help='create music')

    # Add subcommands to music -> create
    music_create_subparsers = music_create_parser.add_subparsers()
github fernnf / vsdnemul / vsdnemul / cli.py View on Github external
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import cmd2
from cmd2 import with_category

from vsdnemul.link import CliLink
from vsdnemul.node import CliNode

CMD_CAT_MANAGER_NODE = "Manager Resources Emulation"


class Cli(cmd2.Cmd):

    def __init__(self, dataplane=None):
        super().__init__(use_ipython=False)
        self.__dp = dataplane
        self.prompt = "[vsdnemul@Root]# "

    def do_exit(self, args):
        return True

    @with_category(CMD_CAT_MANAGER_NODE)
    def do_node(self, args):
        """List all information of the Nodes or Links"""
        i = CliNode(dataplane=self.__dp)
        i.prompt = self.prompt[:-7] + 'Node]# '
        i.cmdloop()
github opencord / voltha / cli / device.py View on Github external
def __init__(self, device_id, get_stub):
        Cmd.__init__(self)
        self.get_stub = get_stub
        self.device_id = device_id
        self.prompt = '(' + self.colorize(
            self.colorize('device {}'.format(device_id), 'red'), 'bold') + ') '
        self.pm_config_last = None
        self.pm_config_dirty = False
github SeldonIO / seldon-server / python / seldon / shell / shell_main.py View on Github external
except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else: raise

def getOpts():
    parser = argparse.ArgumentParser(description='Seldon Shell')
    parser.add_argument('-d', "--debug", action='store_true', help="turn on debugging")
    parser.add_argument('-q', "--quiet", action='store_true', help="only display important messages, useful in non-interactive mode")
    parser.add_argument('--zk-hosts', help="the zookeeper hosts", required=False)
    parser.add_argument('--version', action='store_true', help="print the version", required=False)
    parser.add_argument('args', nargs=argparse.REMAINDER) # catch rest (non-options) as args
    opts = parser.parse_args()
    return opts

class CmdLineApp(Cmd):

    def do_ping(self, arg, opts=None):
        print "pong"

    def do_conf(self, arg, opts=None):
        pp(gdata["conf_data"])

    def do_gdata(self, arg, opts=None):
        pp(gdata)

    def do_db(self, arg, opts=None):
        command_data = {
                'zkdetails' : {'zkroot': gdata['conf_data']['zkroot'], 'zk_client': gdata['zk_client']},
                'help_formatting' : gdata["help_formatting"],
        }
        cmd_db.cmd_db(arg, command_data)
github python-cmd2 / cmd2 / examples / unicode_commands.py View on Github external
#!/usr/bin/env python
# coding=utf-8
"""A simple example demonstrating support for unicode command names.
"""
import math
import cmd2


class UnicodeApp(cmd2.Cmd):
    """Example cmd2 application with unicode command names."""

    def __init__(self):
        super().__init__()
        self.intro = 'Welcome the Unicode example app. Note the full Unicode support:  😇 💩'

    def do_𝛑print(self, _):
        """This command prints 𝛑 to 5 decimal places."""
        self.poutput("𝛑 = {0:.6}".format(math.pi))

    def do_你好(self, arg):
        """This command says hello in Chinese (Mandarin)."""
        self.poutput("你好 " + arg)


if __name__ == '__main__':
github fmagin / angr-cli / angrcli / interaction / explore.py View on Github external
class GUICallbackBaseClass:
    def update_ip(self, ip: int) -> None:
        pass


class BinjaCallback(GUICallbackBaseClass):
    def __init__(self, bv: Any):
        self.bv = bv

    def update_ip(self, ip: int) -> None:
        self.bv.file.navigate(self.bv.file.view, ip)


class ExploreInteractive(cmd2.Cmd):

    intro: ColoredString = Color.redify("[!] Dropping into angr shell\n")
    intro += Color.redify(
        "Available Commands: print, (p)ick, (r)un, (s)tep, stepi, (q)uit"
    )  # type: ignore
    prompt: ColoredString = Color.redify(">>> ")

    def __init__(
        self,
        proj: Project,
        state: SimState,
        gui_callback_object: GUICallbackBaseClass = GUICallbackBaseClass(),
    ):
        super(ExploreInteractive, self).__init__(allow_cli_args=False)
        self.proj = proj
        self.simgr = proj.factory.simulation_manager(state)  # type: SimulationManager