diff options
author | Case Ploeg <caseploog@gmail.com> | 2022-01-27 16:39:15 -0500 |
---|---|---|
committer | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2022-04-13 16:07:05 -0400 |
commit | 49a6b264876895e3020fdebf84232a28d4fe36a5 (patch) | |
tree | 555ed164eb47b9600f063f68146fb2ca3e9436cf | |
parent | 830c7b443aeccd6f620f7144e9bc49aa120fcdf7 (diff) | |
download | cmd2-git-49a6b264876895e3020fdebf84232a28d4fe36a5.tar.gz |
Add an educational postcommand hook
Not necessary for the sake of the example, but might help some curious
individuals get a better feel for how the system works.
-rwxr-xr-x | examples/hooks.py | 15 |
1 files changed, 14 insertions, 1 deletions
diff --git a/examples/hooks.py b/examples/hooks.py index c2739348..9c40cc98 100755 --- a/examples/hooks.py +++ b/examples/hooks.py @@ -34,6 +34,12 @@ class CmdLineApp(cmd2.Cmd): and have them all treated as valid input which prints a list of 10 numbers starting with the number 5. + + We also add a postcommand hook, which updates the shell prompt to show the + raw contents of the Statement after the postparsing hooks are finished. To + use this hook, run `(Cmd) set debug True`. All of the above variations of + the list command should produce the same raw content. + """ # Setting this true makes it run a shell command if a cmd2/cmd command doesn't exist @@ -41,10 +47,11 @@ class CmdLineApp(cmd2.Cmd): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - # register three hooks + # register four hooks self.register_postparsing_hook(self.add_whitespace_hook) self.register_postparsing_hook(self.downcase_hook) self.register_postparsing_hook(self.abbrev_hook) + self.register_postcmd_hook(self.proof_hook) def add_whitespace_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: """A hook to split alphabetic command names immediately followed by a number. @@ -88,6 +95,12 @@ class CmdLineApp(cmd2.Cmd): data.statement = self.statement_parser.parse(raw) return data + def proof_hook(self, data: cmd2.plugin.PostcommandData) -> cmd2.plugin.PostcommandData: + """Update the shell prompt with the new raw statement after postparsing hooks are finished""" + if self.debug: + self.prompt = f'({data.statement.raw})' + return data + @cmd2.with_argument_list def do_list(self, arglist: List[str]) -> None: """Generate a list of 10 numbers.""" |