MCPcopy Create free account
hub / github.com/python-cmd2/cmd2 / SubcommandSet

Class SubcommandSet

tests/test_argparse_subcommands.py:13–58  ·  view source on GitHub ↗

Example cmd2 application where we a base command which has a couple subcommands.

Source from the content-addressed store, hash-verified

11
12
13class SubcommandSet(cmd2.CommandSet):
14 """Example cmd2 application where we a base command which has a couple subcommands."""
15
16 def __init__(self, dummy) -> None:
17 super().__init__()
18
19 # subcommand functions for the base command
20 def base_foo(self, args) -> None:
21 """Foo subcommand of base command"""
22 self._cmd.poutput(args.x * args.y)
23
24 def base_bar(self, args) -> None:
25 """Bar subcommand of base command"""
26 self._cmd.poutput(f"(({args.z}))")
27
28 def base_helpless(self, args) -> None:
29 """Helpless subcommand of base command"""
30 self._cmd.poutput(f"(({args.z}))")
31
32 # create the top-level parser for the base command
33 base_parser = cmd2.Cmd2ArgumentParser()
34 base_subparsers = base_parser.add_subparsers(dest="subcommand", metavar="SUBCOMMAND", required=True)
35
36 # create the parser for the "foo" subcommand
37 parser_foo = base_subparsers.add_parser("foo", help="foo help")
38 parser_foo.add_argument("-x", type=int, default=1, help="integer")
39 parser_foo.add_argument("y", type=float, help="float")
40 parser_foo.set_defaults(func=base_foo)
41
42 # create the parser for the "bar" subcommand
43 parser_bar = base_subparsers.add_parser("bar", help="bar help", aliases=["bar_1", "bar_2"])
44 parser_bar.add_argument("z", help="string")
45 parser_bar.set_defaults(func=base_bar)
46
47 # create the parser for the "helpless" subcommand
48 # This subcommand has aliases and no help text.
49 parser_helpless = base_subparsers.add_parser("helpless", aliases=["helpless_1", "helpless_2"])
50 parser_helpless.add_argument("z", help="string")
51 parser_helpless.set_defaults(func=base_helpless)
52
53 @cmd2.with_argparser(base_parser)
54 def do_base(self, args) -> None:
55 """Base command help"""
56 # Call whatever subcommand function was selected
57 func = args.func
58 func(self, args)
59
60
61@pytest.fixture

Callers 1

subcommand_appFunction · 0.85

Calls

no outgoing calls

Tested by 1

subcommand_appFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…