Skip to content

Commit 49a6b26

Browse files
Case Ploegkmvanbrunt
authored andcommitted
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.
1 parent 830c7b4 commit 49a6b26

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

examples/hooks.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,17 +34,24 @@ class CmdLineApp(cmd2.Cmd):
3434
3535
and have them all treated as valid input which prints a list of 10 numbers
3636
starting with the number 5.
37+
38+
We also add a postcommand hook, which updates the shell prompt to show the
39+
raw contents of the Statement after the postparsing hooks are finished. To
40+
use this hook, run `(Cmd) set debug True`. All of the above variations of
41+
the list command should produce the same raw content.
42+
3743
"""
3844

3945
# Setting this true makes it run a shell command if a cmd2/cmd command doesn't exist
4046
# default_to_shell = True
4147
def __init__(self, *args, **kwargs):
4248
super().__init__(*args, **kwargs)
4349

44-
# register three hooks
50+
# register four hooks
4551
self.register_postparsing_hook(self.add_whitespace_hook)
4652
self.register_postparsing_hook(self.downcase_hook)
4753
self.register_postparsing_hook(self.abbrev_hook)
54+
self.register_postcmd_hook(self.proof_hook)
4855

4956
def add_whitespace_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
5057
"""A hook to split alphabetic command names immediately followed by a number.
@@ -88,6 +95,12 @@ def abbrev_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.Postpars
8895
data.statement = self.statement_parser.parse(raw)
8996
return data
9097

98+
def proof_hook(self, data: cmd2.plugin.PostcommandData) -> cmd2.plugin.PostcommandData:
99+
"""Update the shell prompt with the new raw statement after postparsing hooks are finished"""
100+
if self.debug:
101+
self.prompt = f'({data.statement.raw})'
102+
return data
103+
91104
@cmd2.with_argument_list
92105
def do_list(self, arglist: List[str]) -> None:
93106
"""Generate a list of 10 numbers."""

0 commit comments

Comments
 (0)