Debian Codegraph @

docs/features/commands.md

raw symbols SCIP
1 # Commands
2
3 `cmd2` is designed to make it easy for you to create new commands. These commands form the backbone
4 of your application. If you started writing your application using
5 [cmd](https://docs.python.org/3/library/cmd.html), all the commands you have built will work when
6 you move to `cmd2`. However, there are many more capabilities available in `cmd2` which you can take
7 advantage of to add more robust features to your commands, and which makes your commands easier to
8 write. Before we get to all the good stuff, let's briefly discuss how to create a new command in
9 your application.
10
11 ## Basic Commands
12
13 The simplest `cmd2` application looks like this:
14
15 ```py
16 #!/usr/bin/env python
17 """A simple cmd2 application."""
18 import cmd2
19
20
21 class App(cmd2.Cmd):
22 """A simple cmd2 application."""
23
24
25 if __name__ == '__main__':
26 import sys
27 c = App()
28 sys.exit(c.cmdloop())
29 ```
30
31 This application subclasses [cmd2.Cmd][] but has no code of its own, so all functionality (and
32 there's quite a bit) is inherited. Let's create a simple command in this application called `echo`
33 which outputs any arguments given to it. Add this method to the class:
34
35 ```py
36 def do_echo(self, line):
37 self.poutput(line)
38 ```
39
40 When you type input into the `cmd2` prompt, the first space-delimited word is treated as the command
41 name. `cmd2` looks for a method called `do_commandname`. If it exists, it calls the method, passing
42 the rest of the user input as the first argument. If it doesn't exist `cmd2` prints an error
43 message. As a result of this behavior, the only thing you have to do to create a new command is to
44 define a new method in the class with the appropriate name. This is exactly how you would create a
45 command using the [cmd](https://docs.python.org/3/library/cmd.html) module which is part of the
46 python standard library.
47
48 !!! note
49
50 See [Generating Output](./generating_output.md) if you are unfamiliar with the
51 [poutput()][cmd2.Cmd.poutput] method.
52
53 ## Statements
54
55 A command is passed one argument: a string which contains all the rest of the user input. However,
56 in `cmd2` this string is actually a [Statement][cmd2.Statement] object, which is a subclass of `str`
57 to retain backwards compatibility with `cmd`.
58
59 `cmd2` has a much more sophisticated parsing engine than what's included in the
60 [cmd](https://docs.python.org/3/library/cmd.html) module. This parsing handles:
61
62 - quoted arguments
63 - output redirection and piping
64 - multi-line commands
65 - shortcut, alias, and macro expansion
66
67 In addition to parsing all of these elements from the user input, `cmd2` also has code to make all
68 of these items work; it's almost transparent to you and to the commands you write in your own
69 application. However, by passing your command the `Statement` object instead of just a plain string,
70 you can get visibility into what `cmd2` has done with the user input before your command got it. You
71 can also avoid writing a bunch of parsing code, because `cmd2` gives you access to what it has
72 already parsed.
73
74 A `Statement` object is a subclass of `str` that contains the following attributes:
75
76 **command**
77
78 : Name of the command called. You already know this because of the method `cmd2` called, but it can
79 sometimes be nice to have it in a string, i.e. if you want your error messages to contain the
80 command name.
81
82 **args**
83
84 : A string containing the arguments to the command with output redirection or piping to shell
85 commands removed. It turns out that the "string" value of the `Statement` object has all the output
86 redirection and piping clauses removed as well. Quotes remain in the string.
87
88 **command_and_args**
89
90 : A string of just the command and the arguments, with output redirection or piping to shell
91 commands removed.
92
93 **argv**
94
95 : A list of arguments a-la `sys.argv`, including the command as `argv[0]` and the subsequent
96 arguments as additional items in the list. Quotes around arguments will be stripped as will any
97 output redirection or piping portions of the command.
98
99 **raw**
100
101 : Full input exactly as typed by the user.
102
103 **terminator**
104
105 : Character used to end a multiline command. You can configure multiple termination characters, and
106 this attribute will tell you which one the user typed.
107
108 For many simple commands, like the `echo` command above, you can ignore the `Statement` object and
109 all of its attributes and just use the passed value as a string. You might choose to use the `argv`
110 attribute to do more sophisticated argument processing. Before you go too far down that path, you
111 should check out the [Argument Processing](./argument_processing.md) functionality included with
112 `cmd2`.
113
114 ## Return Values
115
116 Most commands should return nothing (either by omitting a `return` statement, or by `return None`.
117 This indicates that your command is finished (with or without errors), and that `cmd2` should prompt
118 the user for more input.
119
120 If you return `True` or any
121 [Truthy](https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/) value from a command
122 method, that indicates to `cmd2` that it should stop prompting for user input and cleanly exit.
123 `cmd2` already includes a `quit` command, but if you wanted to make another one called `finish` you
124 could:
125
126 ```py
127 def do_finish(self, line):
128 """Exit the application"""
129 return True
130 ```
131
132 ## Exit Codes
133
134 `cmd2` has basic infrastructure to support POSIX shell exit codes. The `cmd2.Cmd` object sets an
135 `exit_code` attribute to zero when it is instantiated. The value of this attribute is returned from
136 the `cmdloop()` call. Therefore, if you don't do anything with this attribute in your code,
137 `cmdloop()` will (almost) always return zero. There are a few built-in `cmd2` commands which set
138 `exit_code` to `1` if an error occurs.
139
140 You can use this capability to easily return your own values to the operating system shell:
141
142 ```py
143 #!/usr/bin/env python
144 """A simple cmd2 application."""
145 import cmd2
146
147
148 class App(cmd2.Cmd):
149 """A simple cmd2 application."""
150
151 def do_bail(self, line):
152 """Exit the application"""
153 self.perror("fatal error, exiting")
154 self.exit_code = 2
155 return True
156
157 if __name__ == '__main__':
158 import sys
159 c = App()
160 sys.exit(c.cmdloop())
161 ```
162
163 If the app was run from the `bash` operating system shell, then you would see the following
164 interaction:
165
166 ```sh
167 (Cmd) bail
168 fatal error, exiting
169 $ echo $?
170 2
171 ```
172
173 Raising `SystemExit(code)` or calling `sys.exit(code)` in a command or hook function also sets
174 `self.exit_code` and stops the program.
175
176 ## Exception Handling
177
178 You may choose to catch and handle any exceptions which occur in a command method. If the command
179 method raises an exception, `cmd2` will catch it and display it for you. The
180 [debug setting](./settings.md#debug) controls how the exception is displayed. If `debug` is `False`,
181 which is the default, `cmd2` will display the exception name and message. If `debug` is `True`,
182 `cmd2` will display a traceback, and then display the exception name and message.
183
184 There are a few exceptions which commands can raise that do not print as described above:
185
186 - `cmd2.exceptions.SkipPostcommandHooks` - all postcommand hooks are skipped and no exception prints
187 - `cmd2.exceptions.Cmd2ArgparseError` - behaves like `SkipPostcommandHooks`
188 - `SystemExit` - `stop` will be set to `True` in an attempt to stop the command loop
189 - `KeyboardInterrupt` - raised if running in a text script and `stop` isn't already True to stop the
190 script
191
192 All other `BaseExceptions` are not caught by `cmd2` and will be raised.
193
194 ## Disabling or Hiding Commands
195
196 See [Disabling Commands](./disable_commands.md) for details of how to:
197
198 - Remove commands included in `cmd2`
199 - Hide commands from the help menu
200 - Dynamically disable and re-enable commands at runtime
201
202 ## Modular Commands and Loading/Unloading Commands
203
204 See [Modular Commands](./modular_commands.md) for details of how to:
205
206 - Define commands in separate [CommandSet][cmd2.CommandSet] modules
207 - Dynamically load or unload commands at runtime