Debian Codegraph @

examples/modular_commandsets.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """A complex example demonstrating a variety of methods to load CommandSets using a mix of command decorators.
3
4 Includes examples of how to integrate tab completion with argparse-based commands.
5 """
6
7 import argparse
8 from collections.abc import Iterable
9
10 from modular_commands.commandset_basic import (
11 BasicCompletionCommandSet,
12 )
13 from modular_commands.commandset_complex import (
14 CommandSetA,
15 )
16 from modular_commands.commandset_custominit import (
17 CustomInitCommandSet,
18 )
19
20 from cmd2 import (
21 Choices,
22 Cmd,
23 Cmd2ArgumentParser,
24 CommandSet,
25 with_argparser,
26 )
27
28
29 class WithCommandSets(Cmd):
30 def __init__(self, command_sets: Iterable[CommandSet] | None = None) -> None:
31 """Cmd2 application to demonstrate a variety of methods for loading CommandSets."""
32 super().__init__(command_sets=command_sets)
33 self.sport_item_strs = ["Bat", "Basket", "Basketball", "Football", "Space Ball"]
34
35 def choices_provider(self) -> Choices:
36 """A choices provider is useful when the choice list is based on instance data of your application."""
37 return Choices.from_values(self.sport_item_strs)
38
39 # Parser for example command
40 example_parser = Cmd2ArgumentParser(
41 description="Command demonstrating tab completion with argparse\nNotice even the flags of this command tab complete"
42 )
43
44 # Tab complete from a list using argparse choices. Set metavar if you don't
45 # want the entire choices list showing in the usage text for this command.
46 example_parser.add_argument(
47 "--choices", choices=["some", "choices", "here"], metavar="CHOICE", help="tab complete using choices"
48 )
49
50 # Tab complete from choices provided by a choices provider
51 example_parser.add_argument(
52 "--choices_provider", choices_provider=choices_provider, help="tab complete using a choices_provider"
53 )
54
55 # Tab complete using a completer
56 example_parser.add_argument("--completer", completer=Cmd.path_complete, help="tab complete using a completer")
57
58 @with_argparser(example_parser)
59 def do_example(self, _: argparse.Namespace) -> None:
60 """An example command."""
61 self.poutput("I do nothing")
62
63
64 if __name__ == "__main__":
65 import sys
66
67 print("Starting")
68 my_sets = [BasicCompletionCommandSet(), CommandSetA(), CustomInitCommandSet("First argument", "Second argument")]
69 app = WithCommandSets(command_sets=my_sets)
70 sys.exit(app.cmdloop())