Debian Codegraph @

docs/features/hooks.md

raw symbols SCIP
1 # Hooks
2
3 The typical way of starting a `cmd2` application is as follows:
4
5 ```py
6 import cmd2
7 class App(cmd2.Cmd):
8 # customized attributes and methods here
9
10 if __name__ == '__main__':
11 app = App()
12 app.cmdloop()
13 ```
14
15 There are several pre-existing methods and attributes which you can tweak to control the overall
16 behavior of your application before, during, and after the command processing loop.
17
18 ## Application Lifecycle Hooks
19
20 You can run a script on initialization by passing the script filename in the `startup_script`
21 parameter of `cmd2.Cmd.__init__`.
22
23 You can also register methods to be called at the beginning of the command loop:
24
25 ```py
26 class App(cmd2.Cmd):
27 def __init__(self, *args, **kwargs):
28 super().__init__(*args, **kwargs)
29 self.register_preloop_hook(self.myhookmethod)
30
31 def myhookmethod(self) -> None:
32 self.poutput("before the loop begins")
33 ```
34
35 To retain backwards compatibility with `cmd.Cmd`, after all registered preloop hooks have been
36 called, the `cmd2.Cmd.preloop` method is called.
37
38 A similar approach allows you to register functions to be called after the command loop has
39 finished:
40
41 ```py
42 class App(cmd2.Cmd):
43 def __init__(self, *args, **kwargs):
44 super().__init__(*args, **kwargs)
45 self.register_postloop_hook(self.myhookmethod)
46
47 def myhookmethod(self) -> None:
48 self.poutput("after the loop ends")
49 ```
50
51 To retain backwards compatibility with `cmd.Cmd`, after all registered postloop hooks have been
52 called, the `cmd2.Cmd.postloop` method is called.
53
54 Preloop and postloop hook methods are not passed any parameters and any return value is ignored.
55
56 The approach of registering hooks instead of overriding methods allows multiple hooks to be called
57 before the command loop begins or ends. Plugin authors should review this page carefully in full for
58 best practices writing hooks.
59
60 ## Application Lifecycle Attributes
61
62 There are numerous attributes on [cmd2.Cmd][] which affect application behavior upon entering or
63 during the command loop:
64
65 - [cmd2.Cmd.intro][] - if provided this serves as the intro banner printed once at start of
66 application, after `cmd2.Cmd.preloop` is called
67 - [cmd2.Cmd.prompt][] - see [Prompt](./prompt.md) for more information
68 - [cmd2.Cmd.continuation_prompt][] - The prompt issued to solicit input for the 2nd and subsequent
69 lines of a [Multiline Command](./multiline_commands.md)
70 - [cmd2.Cmd.echo][] - if `True` write the prompt and the command into the output stream
71
72 In addition, several arguments to [cmd2.Cmd.\_\_init\_\_][cmd2.Cmd.__init__] also affect the command
73 loop behavior:
74
75 - `allow_cli_args` - allows commands to be specified on the operating system command line which are
76 executed before the command processing loop begins
77 - `startup_script` - run a script on initialization. See [Scripting](./scripting.md) for more
78 information
79
80 ## Command Processing Loop
81
82 When you call [cmd2.Cmd.cmdloop][], the following sequence of events are repeated until the
83 application exits:
84
85 1. Start the `prompt-toolkit` event loop
86 1. Call [cmd2.Cmd.pre_prompt][] for any behavior that should happen after event loop starts but
87 before prompt is displayed
88 1. Output the prompt
89 1. Accept user input
90 1. Parse user input into a [cmd2.Statement][] object
91 1. Call methods registered with [cmd2.Cmd.register_postparsing_hook][]
92 1. Redirect output, if user asked for it and it's allowed
93 1. Start timer
94 1. Call methods registered with [cmd2.Cmd.register_precmd_hook][]
95 1. Call [cmd2.Cmd.precmd][] - for backwards compatibility with `cmd.Cmd`
96 1. Add statement to [History](./history.md)
97 1. Call `do_command` method
98 1. Call methods registered with [cmd2.Cmd.register_postcmd_hook][]
99 1. Call [cmd2.Cmd.postcmd][] - for backwards compatibility with `cmd.Cmd`
100 1. Stop timer and display the elapsed time
101 1. Stop redirecting output if it was redirected
102 1. Call methods registered with [cmd2.Cmd.register_cmdfinalization_hook][]
103
104 By registering hook methods, multiple steps allow you to run code during, and control the flow of
105 the command processing loop. Be aware that plugins also utilize these hooks, so there may be code
106 running that is not directly part of your application code. Methods registered for a hook are called
107 in the order they were registered. You can register a function more than once, and it will be called
108 each time it was registered.
109
110 Postparsing, precommand, and postcommand hook methods share some common ways to influence the
111 command processing loop.
112
113 If a hook raises an exception:
114
115 - no more hooks (except command finalization hooks) of any kind will be called
116 - if the command has not yet been executed, it will not be executed
117 - the exception message will be displayed for the user.
118
119 Specific types of hook methods have additional options as described below.
120
121 ## Postparsing Hooks
122
123 Postparsing hooks are called after the user input has been parsed but before execution of the
124 command. These hooks can be used to:
125
126 - modify the user input
127 - run code before every command executes
128 - cancel execution of the current command
129 - exit the application
130
131 When postparsing hooks are called, output has not been redirected, nor has the timer for command
132 execution been started.
133
134 To define and register a postparsing hook, do the following:
135
136 ```py
137 class App(cmd2.Cmd):
138 def __init__(self, *args, **kwargs):
139 super().__init__(*args, **kwargs)
140 self.register_postparsing_hook(self.myhookmethod)
141
142 def myhookmethod(self, params: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
143 # the statement object created from the user input
144 # is available as params.statement
145 return params
146 ```
147
148 `cmd2.Cmd.register_postparsing_hook` checks the method signature of the passed callable, and raises
149 a `TypeError` if it has the wrong number of parameters. It will also raise a `TypeError` if the
150 passed parameter and return value are not annotated as `PostparsingData`.
151
152 The hook method will be passed one parameter, a [cmd2.plugin.PostparsingData][] object which we will
153 refer to as `params`. `params` contains two attributes. `params.statement` is a `cmd2.Statement`
154 object which describes the parsed user input. There are many useful attributes in the
155 `cmd2.Statement` object, including `.raw` which contains exactly what the user typed. `params.stop`
156 is set to `False` by default.
157
158 The hook method must return a `cmd2.plugin.PostparsingData` object, and it is very convenient to
159 just return the object passed into the hook method. The hook method may modify the attributes of the
160 object to influence the behavior of the application. If `params.stop` is set to `True`, a fatal
161 failure is triggered prior to execution of the command, and the application exits.
162
163 To modify the user input, you create a new `cmd2.Statement` object and return it in
164 `params.statement`. Don't try and directly modify the contents of a `cmd2.Statement` object, there
165 be dragons. Instead, use the various attributes in a `cmd2.Statement` object to construct a new
166 string, and then parse that string to create a new `cmd2.Statement` object.
167
168 `cmd2.Cmd` uses an instance of [cmd2.parsing.StatementParser][] to parse user input. This instance
169 has been configured with the proper command terminators, multiline commands, and other parsing
170 related settings. This instance is available as the `cmd2.Cmd.statement_parser` attribute. Here's a
171 simple example which shows the proper technique:
172
173 ```py
174 def myhookmethod(self, params: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
175 if not '|' in params.statement.raw:
176 newinput = params.statement.raw + ' | less'
177 params.statement = self.statement_parser.parse(newinput)
178 return params
179 ```
180
181 If a postparsing hook returns a `cmd2.plugin.PostparsingData` object with the
182 `cmd2.plugin.PostparsingData.stop` attribute set to `True`:
183
184 - no more hooks of any kind (except [Command Finalization Hooks](#command-finalization-hooks)) will
185 be called
186 - the command will not be executed
187 - no error message will be displayed to the user
188 - the application will exit
189
190 ## Precommand Hooks
191
192 Precommand hooks can modify the user input, but cannot request the application terminate. If your
193 hook needs to be able to exit the application, you should implement it as a postparsing hook.
194
195 Once output is redirected and the timer is started, all the hooks registered with
196 `cmd2.Cmd.register_precmd_hook` are called. Here's how to do it:
197
198 ```py
199 class App(cmd2.Cmd):
200 def __init__(self, *args, **kwargs):
201 super().__init__(*args, **kwargs)
202 self.register_precmd_hook(self.myhookmethod)
203
204 def myhookmethod(self, data: cmd2.plugin.PrecommandData) -> cmd2.plugin.PrecommandData:
205 # the statement object created from the user input
206 # is available as data.statement
207 return data
208 ```
209
210 `cmd2.Cmd.register_precmd_hook` checks the method signature of the passed callable, and raises a
211 `TypeError` if it has the wrong number of parameters. It will also raise a `TypeError` if the
212 parameters and return value are not annotated as `PrecommandData`.
213
214 You may choose to modify the user input by creating a new `cmd2.Statement` with different properties
215 (see above). If you do so, assign your new `cmd2.Statement` object to `data.statement`.
216
217 The precommand hook must return a [cmd2.plugin.PrecommandData][] object. You don't have to create
218 this object from scratch, you can just return the one passed into the hook.
219
220 After all registered precommand hooks have been called, `cmd2.Cmd.precmd` will be called. To retain
221 full backward compatibility with `cmd.Cmd`, this method is passed a `cmd2.Statement`, not a
222 `cmd2.plugin.PrecommandData` object.
223
224 ## Postcommand Hooks
225
226 Once the command method has returned (i.e. the `do_command(self, statement) method` has been called
227 and returns, all postcommand hooks are called. If output was redirected by the user, it is still
228 redirected, and the command timer is still running.
229
230 Here's how to define and register a postcommand hook:
231
232 ```py
233 class App(cmd2.Cmd):
234 def __init__(self, *args, **kwargs):
235 super().__init__(*args, **kwargs)
236 self.register_postcmd_hook(self.myhookmethod)
237
238 def myhookmethod(self, data: cmd2.plugin.PostcommandData) -> cmd2.plugin.PostcommandData:
239 return data
240 ```
241
242 Your hook will be passed a [cmd2.plugin.PostcommandData][] object, which has a
243 `cmd2.plugin.PostcommandData.statement` attribute that describes the command which was executed. If
244 your postcommand hook method gets called, you are guaranteed that the command method was called, and
245 that it didn't raise an exception.
246
247 If any postcommand hook raises an exception, the exception will be displayed to the user, and no
248 further postcommand hook methods will be called. Command finalization hooks, if any, will be called.
249
250 After all registered postcommand hooks have been called, `self.postcmd` will be called to retain
251 full backward compatibility with `cmd.Cmd`.
252
253 If any postcommand hook (registered or `self.postcmd`) returns a `cmd2.plugin.PostcommandData`
254 object with the stop attribute set to `True`, subsequent postcommand hooks will still be called, as
255 will the command finalization hooks, but once those hooks have all been called, the application will
256 terminate. Likewise, if `self.postcmd` returns `True`, the command finalization hooks will be called
257 before the application terminates.
258
259 Any postcommand hook can change the value of the `stop` attribute before returning it, and the
260 modified value will be passed to the next postcommand hook. The value returned by the final
261 postcommand hook will be passed to the command finalization hooks, which may further modify the
262 value. If your hook blindly returns `False`, a prior hook's request to exit the application will not
263 be honored. It's best to return the value you were passed unless you have a compelling reason to do
264 otherwise.
265
266 To purposefully and silently skip postcommand hooks, commands can raise any of the following
267 exceptions.
268
269 - [cmd2.exceptions.SkipPostcommandHooks][]
270 - [cmd2.exceptions.Cmd2ArgparseError][]
271
272 ## Command Finalization Hooks
273
274 Command finalization hooks are called even if one of the other types of hooks or the command method
275 raise an exception. Here's how to create and register a command finalization hook:
276
277 ```py
278 class App(cmd2.Cmd):
279 def __init__(self, *args, **kwargs):
280 super().__init__(*args, **kwargs)
281 self.register_cmdfinalization_hook(self.myhookmethod)
282
283 def myhookmethod(self, data: cmd2.plugin.CommandFinalizationData) -> cmd2.plugin.CommandFinalizationData:
284 return data
285 ```
286
287 Command Finalization hooks must check whether the `cmd2.plugin.CommandFinalizationData.statement`
288 attribute of the passed [cmd2.plugin.CommandFinalizationData][] object contains a value. There are
289 certain circumstances where these hooks may be called before the user input has been parsed, so you
290 can't always rely on having a `cmd2.plugin.CommandFinalizationData.statement`.
291
292 If any prior postparsing or precommand hook has requested the application to terminate, the value of
293 the `cmd2.plugin.CommandFinalizationData.stop` attribute passed to the first command finalization
294 hook will be `True`. Any command finalization hook can change the value of the
295 `cmd2.plugin.CommandFinalizationData.stop` attribute before returning it, and the modified value
296 will be passed to the next command finalization hook. The value returned by the final command
297 finalization hook will determine whether the application terminates or not.
298
299 This approach to command finalization hooks can be powerful, but it can also cause problems. If your
300 hook blindly returns `False`, a prior hook's request to exit the application will not be honored.
301 It's best to return the value you were passed unless you have a compelling reason to do otherwise.
302
303 If any command finalization hook raises an exception, no more command finalization hooks will be
304 called. If the last hook to return a value returned `True`, then the exception will be rendered, and
305 the application will terminate.