Debian Codegraph @

docs/examples/getting_started.md

raw symbols SCIP
1 # Getting Started
2
3 Here's a quick walkthrough of the simple
4 [getting_started.py](https://github.com/python-cmd2/cmd2/blob/main/examples/getting_started.py)
5 example application which demonstrates many features of `cmd2`:
6
7 - [Settings](../features/settings.md)
8 - [Commands](../features/commands.md)
9 - [Argument Processing](../features/argument_processing.md)
10 - [Generating Output](../features/generating_output.md)
11 - [Help](../features/help.md)
12 - [Shortcuts](../features/shortcuts_aliases_macros.md#shortcuts)
13 - [Multiline Commands](../features/multiline_commands.md)
14 - [History](../features/history.md)
15 - [Bottom Toolbar](../features/prompt.md#bottom-toolbar)
16
17 If you don't want to type as we go, here is the complete source (you can click to expand and then
18 click the **Copy** button in the top-right):
19
20 !!! example "getting_started.py"
21
22 ```py
23 --8<-- "examples/getting_started.py"
24 ```
25
26 ## Basic Application
27
28 First we need to create a new `cmd2` application. Create a new file `getting_started.py` with the
29 following contents:
30
31 ```py
32 #!/usr/bin/env python
33 """A basic cmd2 application."""
34 import cmd2
35
36
37 class BasicApp(cmd2.Cmd):
38 """Cmd2 application to demonstrate many common features."""
39
40
41 if __name__ == '__main__':
42 import sys
43 app = BasicApp()
44 sys.exit(app.cmdloop())
45 ```
46
47 We have a new class `BasicApp` which is a subclass of [cmd2.Cmd][]. When we tell Python to run our
48 file like this:
49
50 ```shell
51 $ python getting_started.py
52 ```
53
54 The application creates an instance of our class, and calls the [cmd2.Cmd.cmdloop][] method. This
55 method accepts user input and runs commands based on that input. Because we subclassed `cmd2.Cmd`,
56 our new app already has a bunch of built-in features.
57
58 Congratulations, you have a working `cmd2` app. You can run it, and then type `quit` to exit.
59
60 ## Create a New Setting
61
62 Before we create our first command, we are going to add a new setting to this app. `cmd2` includes
63 robust support for [Settings](../features/settings.md). You configure settings during object
64 initialization, so we need to add an initializer to our class:
65
66 ```py
67 def __init__(self):
68 super().__init__()
69
70 # Make maxrepeats settable at runtime
71 self.maxrepeats = 3
72 self.add_settable(cmd2.Settable('maxrepeats', int, 'max repetitions for speak command', self))
73 ```
74
75 In that initializer, the first thing to do is to make sure we initialize `cmd2`. That's what the
76 `super().__init__()` line does. Next create an attribute to hold the setting. Finally, call the
77 [cmd2.Cmd.add_settable][] method with a new instance of a [cmd2.utils.Settable][] class. Now if you
78 run the script, and enter the `set` command to see the settings, like this:
79
80 ```shell
81 $ python getting_started.py
82 (Cmd) set
83 ```
84
85 you will see our `maxrepeats` setting show up with its default value of `3`.
86
87 ## Create A Command
88
89 Now we will create our first command, called `speak`, which will echo back whatever we tell it to
90 say. We are going to use an [argument processor](../features/argument_processing.md) so the `speak`
91 command can shout and talk Pig Latin. We will also use some built in methods for
92 [generating output](../features/generating_output.md). Add this code to `getting_started.py`, so
93 that the `speak_parser` attribute and the `do_speak()` method are part of the `BasicApp()` class:
94
95 ```py
96 speak_parser = cmd2.Cmd2ArgumentParser()
97 speak_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
98 speak_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
99 speak_parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
100 speak_parser.add_argument('words', nargs='+', help='words to say')
101
102 @cmd2.with_argparser(speak_parser)
103 def do_speak(self, args):
104 """Repeats what you tell me to."""
105 words = []
106 for word in args.words:
107 if args.piglatin:
108 word = '%s%say' % (word[1:], word[0])
109 if args.shout:
110 word = word.upper()
111 words.append(word)
112 repetitions = args.repeat or 1
113 for _ in range(min(repetitions, self.maxrepeats)):
114 # .poutput handles newlines, and accommodates output redirection too
115 self.poutput(' '.join(words))
116 ```
117
118 Up at the top of the script, you'll also need to add:
119
120 ```py
121 import argparse
122 ```
123
124 There's a bit to unpack here, so let's walk through it. We created `speak_parser`, which uses the
125 [argparse](https://docs.python.org/3/library/argparse.html) module from the Python standard library
126 to parse command line input from a user. So far, there is nothing specific to `cmd2`.
127
128 There is also a new method called `do_speak()`. In both
129 [cmd](https://docs.python.org/3/library/cmd.html) and `cmd2`, methods that start with `do_` become
130 new commands, so by defining this method we have created a command called `speak`.
131
132 Note the `cmd2.decorators.with_argparser` decorator on the `do_speak()` method. This decorator does
133 3 useful things for us:
134
135 1. It tells `cmd2` to process all input for the `speak` command using the argparser we defined. If
136 the user input doesn't meet the requirements defined by the argparser, then an error will be
137 displayed for the user.
138 1. It alters our `do_speak` method so that instead of receiving the raw user input as a parameter,
139 we receive the namespace from the argument parser.
140 1. It creates a help message for us based on the argparser.
141
142 You can see in the body of the method how we use the namespace from the argparser (passed in as the
143 variable `args`). We build a list of words which we will output, honoring both the `--piglatin` and
144 `--shout` options.
145
146 At the end of the method, we use our `maxrepeats` setting as an upper limit to the number of times
147 we will print the output.
148
149 The last thing you'll notice is that we used the `self.poutput()` method to display our output.
150 `poutput()` is a method provided by `cmd2`, which I strongly recommend you use any time you want to
151 [generate output](../features/generating_output.md). It provides the following benefits:
152
153 1. Allows the user to redirect output to a text file or pipe it to a shell process
154 1. Gracefully handles `BrokenPipeError` exceptions for redirected output
155 1. Honors the setting to [strip embedded ANSI sequences](../features/settings.md#allow_style)
156 (typically used for background and foreground colors)
157
158 Go run the script again, and try out the `speak` command. Try typing `help speak`, and you will see
159 a lovely usage message describing the various options for the command.
160
161 With those few lines of code, we created a [command](../features/commands.md), used an
162 [Argument Processor](../features/argument_processing.md), added a nice
163 [help message](../features/help.md) for our users, and
164 [generated some output](../features/generating_output.md).
165
166 ## Shortcuts
167
168 `cmd2` has several capabilities to simplify repetitive user input:
169 [Shortcuts, Aliases, and Macros](../features/shortcuts_aliases_macros.md). Let's add a shortcut to
170 our application. Shortcuts are character strings that can be used instead of a command name. For
171 example, `cmd2` has support for a shortcut `!` which runs the `shell` command. So instead of typing
172 this:
173
174 ```shell
175 (Cmd) shell ls -al
176 ```
177
178 you can type this:
179
180 ```shell
181 (Cmd) !ls -al
182 ```
183
184 Let's add a shortcut for our `speak` command. Change the `__init__()` method so it looks like this:
185
186 ```py
187 def __init__(self):
188 shortcuts = cmd2.DEFAULT_SHORTCUTS
189 shortcuts.update({'&': 'speak'})
190 super().__init__(shortcuts=shortcuts)
191
192 # Make maxrepeats settable at runtime
193 self.maxrepeats = 3
194 self.add_settable(cmd2.Settable('maxrepeats', int, 'max repetitions for speak command', self))
195 ```
196
197 Shortcuts are passed to the `cmd2` initializer, and if you want the built-in shortcuts of `cmd2` you
198 have to pass them. These shortcuts are defined as a dictionary, with the key being the shortcut, and
199 the value containing the command. When using the default shortcuts and adding your own, it's a good
200 idea to use the `.update()` method to modify the dictionary. This way, if you add a shortcut that
201 happens to already be in the default set, yours will override, and you won't get any errors at
202 runtime.
203
204 Run your app again, and type:
205
206 ```shell
207 (Cmd) shortcuts
208 ```
209
210 to see the list of all the shortcuts, including the one for speak that we just created.
211
212 ## Multiline Commands
213
214 Some use cases benefit from commands that span more than one line. For example, you might want the
215 ability for your user to type in a SQL command, which can often span lines and which are terminated
216 with a semicolon. Let's add a [multiline command](../features/multiline_commands.md) to our
217 application. First we'll create a new command called `orate`. This code shows both the definition of
218 our `speak` command, and the `orate` command:
219
220 ```py
221 @cmd2.with_argparser(speak_parser)
222 def do_speak(self, args):
223 """Repeats what you tell me to."""
224 words = []
225 for word in args.words:
226 if args.piglatin:
227 word = '%s%say' % (word[1:], word[0])
228 if args.shout:
229 word = word.upper()
230 words.append(word)
231 repetitions = args.repeat or 1
232 for _ in range(min(repetitions, self.maxrepeats)):
233 # .poutput handles newlines, and accommodates output redirection too
234 self.poutput(' '.join(words))
235
236 # orate is a synonym for speak which takes multiline input
237 do_orate = do_speak
238 ```
239
240 With the new command created, we need to tell `cmd2` to treat that command as a multi-line command.
241 Modify the super initialization line to look like this:
242
243 ```py
244 super().__init__(multiline_commands=['orate'], shortcuts=shortcuts)
245 ```
246
247 Now when you run the example, you can type something like this:
248
249 ```text
250 (Cmd) orate O for a Muse of fire, that would ascend
251 > The brightest heaven of invention,
252 > A kingdom for a stage, princes to act
253 > And monarchs to behold the swelling scene! ;
254 ```
255
256 Notice the prompt changes to indicate that input is still ongoing. `cmd2` will continue prompting
257 for input until it sees an unquoted semicolon (the default multi-line command termination
258 character).
259
260 ## History
261
262 `cmd2` tracks the history of the commands that users enter. As a developer, you don't need to do
263 anything to enable this functionality, you get it for free. If you want the history of commands to
264 persist between invocations of your application, you'll need to do a little work. The
265 [History](../features/history.md) page has all the details.
266
267 Users can access command history using two methods:
268
269 - The [prompt-toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) library which
270 provides a pure Python replacement for the
271 [GNU readline library](https://en.wikipedia.org/wiki/GNU_Readline) which is fully cross-platform
272 compatible
273 - The `history` command which is built-in to `cmd2`
274
275 From the prompt in a `cmd2`-based application, you can press `Control-p` to move to the previously
276 entered command, and `Control-n` to move to the next command. You can also search through the
277 command history using `Control-r`.
278
279 By default, `prompt-toolkit` provides Emacs-style key bindings which will be familiar to users of
280 the GNU Readline library. You can refer to the
281 [readline cheat sheet](http://readline.kablamo.org/emacs.html) or you can dig into the
282 [Prompt Toolkit User Manual](https://python-prompt-toolkit.readthedocs.io/en/stable/pages/advanced_topics/key_bindings.html)
283 for all the details, including instructions for customizing the key bindings.
284
285 The `history` command allows a user to view the command history, and select commands from history by
286 number, range, string search, or regular expression. With the selected commands, users can:
287
288 - Re-run the commands
289 - Edit the selected commands in a text editor, and run them after the text editor exits
290 - Save the commands to a file
291 - Run the commands, saving both the commands and their output to a file
292
293 Learn more about the `history` command by typing `history -h` at any `cmd2` input prompt, or by
294 exploring [Command History For Users](../features/history.md#for-users).
295
296 ## Conclusion
297
298 You've just created a simple, but functional command line application. With minimal work on your
299 part, the application leverages many robust features of `cmd2`. To learn more you can:
300
301 - Dive into all of the [Features](../features/index.md) that `cmd2` provides
302 - Look at more [Examples](../examples/index.md)
303 - Browse the [API Reference](../api/index.md)