Instead of defining all commands in a single cmd2.Cmd class, you can group them into cmd2.CommandSet objects. This allows for better organization, encapsulation of state, and easier plugin development.
Key Rules for CommandSet Methods:
- Command methods: Must be prefixed with
do_. - Help methods: Must be prefixed with
help_. - Completer methods: Must be prefixed with
complete_. self context: Inside a CommandSet, self refers to the CommandSet instance, not the main cmd2.Cmd instance. To access the main application, use self._cmd.
Automatic Command Discovery
To automatically discover and load all CommandSet objects that are imported into your application, initialize your cmd2.Cmd subclass with auto_load_commands=True.
import cmd2
from cmd2 import CommandSet
class ExampleApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
# Setting auto_load_commands=True enables automatic discovery
super().__init__(*args, auto_load_commands=True, **kwargs)
class AutoLoadCommandSet(CommandSet[ExampleApp]):
def do_hello(self, _: cmd2.Statement):
"""Hello Command."""
# Access the main app via self._cmd
self._cmd.poutput('Hello')