Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :mod:`cmd` --- Support for line-oriented command interpreters |
| 2 | ============================================================= |
| 3 | |
| 4 | .. module:: cmd |
| 5 | :synopsis: Build line-oriented command interpreters. |
| 6 | .. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com> |
| 7 | |
Raymond Hettinger | 1048094 | 2011-01-10 03:26:08 +0000 | [diff] [blame] | 8 | **Source code:** :source:`Lib/cmd.py` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 9 | |
Raymond Hettinger | 4f707fd | 2011-01-10 19:54:11 +0000 | [diff] [blame] | 10 | -------------- |
| 11 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 12 | The :class:`Cmd` class provides a simple framework for writing line-oriented |
| 13 | command interpreters. These are often useful for test harnesses, administrative |
| 14 | tools, and prototypes that will later be wrapped in a more sophisticated |
| 15 | interface. |
| 16 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 17 | .. class:: Cmd(completekey='tab', stdin=None, stdout=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 18 | |
| 19 | A :class:`Cmd` instance or subclass instance is a line-oriented interpreter |
| 20 | framework. There is no good reason to instantiate :class:`Cmd` itself; rather, |
| 21 | it's useful as a superclass of an interpreter class you define yourself in order |
| 22 | to inherit :class:`Cmd`'s methods and encapsulate action methods. |
| 23 | |
| 24 | The optional argument *completekey* is the :mod:`readline` name of a completion |
| 25 | key; it defaults to :kbd:`Tab`. If *completekey* is not :const:`None` and |
| 26 | :mod:`readline` is available, command completion is done automatically. |
| 27 | |
| 28 | The optional arguments *stdin* and *stdout* specify the input and output file |
| 29 | objects that the Cmd instance or subclass instance will use for input and |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 30 | output. If not specified, they will default to :data:`sys.stdin` and |
| 31 | :data:`sys.stdout`. |
| 32 | |
| 33 | If you want a given *stdin* to be used, make sure to set the instance's |
| 34 | :attr:`use_rawinput` attribute to ``False``, otherwise *stdin* will be |
| 35 | ignored. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 36 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 37 | |
| 38 | .. _cmd-objects: |
| 39 | |
| 40 | Cmd Objects |
| 41 | ----------- |
| 42 | |
| 43 | A :class:`Cmd` instance has the following methods: |
| 44 | |
| 45 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 46 | .. method:: Cmd.cmdloop(intro=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 47 | |
| 48 | Repeatedly issue a prompt, accept input, parse an initial prefix off the |
| 49 | received input, and dispatch to action methods, passing them the remainder of |
| 50 | the line as argument. |
| 51 | |
| 52 | The optional argument is a banner or intro string to be issued before the first |
Senthil Kumaran | a6bac95 | 2011-07-04 11:28:30 -0700 | [diff] [blame] | 53 | prompt (this overrides the :attr:`intro` class attribute). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 54 | |
| 55 | If the :mod:`readline` module is loaded, input will automatically inherit |
| 56 | :program:`bash`\ -like history-list editing (e.g. :kbd:`Control-P` scrolls back |
| 57 | to the last command, :kbd:`Control-N` forward to the next one, :kbd:`Control-F` |
| 58 | moves the cursor to the right non-destructively, :kbd:`Control-B` moves the |
| 59 | cursor to the left non-destructively, etc.). |
| 60 | |
| 61 | An end-of-file on input is passed back as the string ``'EOF'``. |
| 62 | |
| 63 | An interpreter instance will recognize a command name ``foo`` if and only if it |
| 64 | has a method :meth:`do_foo`. As a special case, a line beginning with the |
| 65 | character ``'?'`` is dispatched to the method :meth:`do_help`. As another |
| 66 | special case, a line beginning with the character ``'!'`` is dispatched to the |
| 67 | method :meth:`do_shell` (if such a method is defined). |
| 68 | |
| 69 | This method will return when the :meth:`postcmd` method returns a true value. |
| 70 | The *stop* argument to :meth:`postcmd` is the return value from the command's |
| 71 | corresponding :meth:`do_\*` method. |
| 72 | |
| 73 | If completion is enabled, completing commands will be done automatically, and |
| 74 | completing of commands args is done by calling :meth:`complete_foo` with |
| 75 | arguments *text*, *line*, *begidx*, and *endidx*. *text* is the string prefix |
| 76 | we are attempting to match: all returned matches must begin with it. *line* is |
| 77 | the current input line with leading whitespace removed, *begidx* and *endidx* |
| 78 | are the beginning and ending indexes of the prefix text, which could be used to |
| 79 | provide different completion depending upon which position the argument is in. |
| 80 | |
Georg Brandl | b2566cf | 2010-08-02 20:27:20 +0000 | [diff] [blame] | 81 | All subclasses of :class:`Cmd` inherit a predefined :meth:`do_help`. This |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 82 | method, called with an argument ``'bar'``, invokes the corresponding method |
Georg Brandl | b2566cf | 2010-08-02 20:27:20 +0000 | [diff] [blame] | 83 | :meth:`help_bar`, and if that is not present, prints the docstring of |
| 84 | :meth:`do_bar`, if available. With no argument, :meth:`do_help` lists all |
| 85 | available help topics (that is, all commands with corresponding |
| 86 | :meth:`help_\*` methods or commands that have docstrings), and also lists any |
| 87 | undocumented commands. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 88 | |
| 89 | |
| 90 | .. method:: Cmd.onecmd(str) |
| 91 | |
| 92 | Interpret the argument as though it had been typed in response to the prompt. |
| 93 | This may be overridden, but should not normally need to be; see the |
| 94 | :meth:`precmd` and :meth:`postcmd` methods for useful execution hooks. The |
| 95 | return value is a flag indicating whether interpretation of commands by the |
| 96 | interpreter should stop. If there is a :meth:`do_\*` method for the command |
| 97 | *str*, the return value of that method is returned, otherwise the return value |
| 98 | from the :meth:`default` method is returned. |
| 99 | |
| 100 | |
| 101 | .. method:: Cmd.emptyline() |
| 102 | |
| 103 | Method called when an empty line is entered in response to the prompt. If this |
| 104 | method is not overridden, it repeats the last nonempty command entered. |
| 105 | |
| 106 | |
| 107 | .. method:: Cmd.default(line) |
| 108 | |
| 109 | Method called on an input line when the command prefix is not recognized. If |
| 110 | this method is not overridden, it prints an error message and returns. |
| 111 | |
| 112 | |
| 113 | .. method:: Cmd.completedefault(text, line, begidx, endidx) |
| 114 | |
| 115 | Method called to complete an input line when no command-specific |
| 116 | :meth:`complete_\*` method is available. By default, it returns an empty list. |
| 117 | |
| 118 | |
| 119 | .. method:: Cmd.precmd(line) |
| 120 | |
| 121 | Hook method executed just before the command line *line* is interpreted, but |
| 122 | after the input prompt is generated and issued. This method is a stub in |
| 123 | :class:`Cmd`; it exists to be overridden by subclasses. The return value is |
| 124 | used as the command which will be executed by the :meth:`onecmd` method; the |
| 125 | :meth:`precmd` implementation may re-write the command or simply return *line* |
| 126 | unchanged. |
| 127 | |
| 128 | |
| 129 | .. method:: Cmd.postcmd(stop, line) |
| 130 | |
| 131 | Hook method executed just after a command dispatch is finished. This method is |
| 132 | a stub in :class:`Cmd`; it exists to be overridden by subclasses. *line* is the |
| 133 | command line which was executed, and *stop* is a flag which indicates whether |
| 134 | execution will be terminated after the call to :meth:`postcmd`; this will be the |
| 135 | return value of the :meth:`onecmd` method. The return value of this method will |
| 136 | be used as the new value for the internal flag which corresponds to *stop*; |
| 137 | returning false will cause interpretation to continue. |
| 138 | |
| 139 | |
| 140 | .. method:: Cmd.preloop() |
| 141 | |
| 142 | Hook method executed once when :meth:`cmdloop` is called. This method is a stub |
| 143 | in :class:`Cmd`; it exists to be overridden by subclasses. |
| 144 | |
| 145 | |
| 146 | .. method:: Cmd.postloop() |
| 147 | |
| 148 | Hook method executed once when :meth:`cmdloop` is about to return. This method |
| 149 | is a stub in :class:`Cmd`; it exists to be overridden by subclasses. |
| 150 | |
| 151 | Instances of :class:`Cmd` subclasses have some public instance variables: |
| 152 | |
| 153 | |
| 154 | .. attribute:: Cmd.prompt |
| 155 | |
| 156 | The prompt issued to solicit input. |
| 157 | |
| 158 | |
| 159 | .. attribute:: Cmd.identchars |
| 160 | |
| 161 | The string of characters accepted for the command prefix. |
| 162 | |
| 163 | |
| 164 | .. attribute:: Cmd.lastcmd |
| 165 | |
| 166 | The last nonempty command prefix seen. |
| 167 | |
| 168 | |
| 169 | .. attribute:: Cmd.intro |
| 170 | |
| 171 | A string to issue as an intro or banner. May be overridden by giving the |
| 172 | :meth:`cmdloop` method an argument. |
| 173 | |
| 174 | |
| 175 | .. attribute:: Cmd.doc_header |
| 176 | |
| 177 | The header to issue if the help output has a section for documented commands. |
| 178 | |
| 179 | |
| 180 | .. attribute:: Cmd.misc_header |
| 181 | |
| 182 | The header to issue if the help output has a section for miscellaneous help |
| 183 | topics (that is, there are :meth:`help_\*` methods without corresponding |
| 184 | :meth:`do_\*` methods). |
| 185 | |
| 186 | |
| 187 | .. attribute:: Cmd.undoc_header |
| 188 | |
| 189 | The header to issue if the help output has a section for undocumented commands |
| 190 | (that is, there are :meth:`do_\*` methods without corresponding :meth:`help_\*` |
| 191 | methods). |
| 192 | |
| 193 | |
| 194 | .. attribute:: Cmd.ruler |
| 195 | |
| 196 | The character used to draw separator lines under the help-message headers. If |
| 197 | empty, no ruler line is drawn. It defaults to ``'='``. |
| 198 | |
| 199 | |
| 200 | .. attribute:: Cmd.use_rawinput |
| 201 | |
| 202 | A flag, defaulting to true. If true, :meth:`cmdloop` uses :func:`input` to |
| 203 | display a prompt and read the next command; if false, :meth:`sys.stdout.write` |
| 204 | and :meth:`sys.stdin.readline` are used. (This means that by importing |
| 205 | :mod:`readline`, on systems that support it, the interpreter will automatically |
| 206 | support :program:`Emacs`\ -like line editing and command-history keystrokes.) |
| 207 | |
Éric Araujo | 6e7d0ba | 2011-08-19 00:39:57 +0200 | [diff] [blame] | 208 | |
| 209 | .. _cmd-example: |
| 210 | |
Raymond Hettinger | bd889e8 | 2010-09-09 01:40:50 +0000 | [diff] [blame] | 211 | Cmd Example |
Alexander Belopolsky | f0a0d14 | 2010-10-27 03:06:43 +0000 | [diff] [blame] | 212 | ----------- |
Raymond Hettinger | bd889e8 | 2010-09-09 01:40:50 +0000 | [diff] [blame] | 213 | |
| 214 | .. sectionauthor:: Raymond Hettinger <python at rcn dot com> |
| 215 | |
| 216 | The :mod:`cmd` module is mainly useful for building custom shells that let a |
| 217 | user work with a program interactively. |
| 218 | |
| 219 | This section presents a simple example of how to build a shell around a few of |
| 220 | the commands in the :mod:`turtle` module. |
| 221 | |
| 222 | Basic turtle commands such as :meth:`~turtle.forward` are added to a |
| 223 | :class:`Cmd` subclass with method named :meth:`do_forward`. The argument is |
| 224 | converted to a number and dispatched to the turtle module. The docstring is |
| 225 | used in the help utility provided by the shell. |
| 226 | |
| 227 | The example also includes a basic record and playback facility implemented with |
| 228 | the :meth:`~Cmd.precmd` method which is responsible for converting the input to |
| 229 | lowercase and writing the commands to a file. The :meth:`do_playback` method |
| 230 | reads the file and adds the recorded commands to the :attr:`cmdqueue` for |
| 231 | immediate playback:: |
| 232 | |
| 233 | import cmd, sys |
| 234 | from turtle import * |
| 235 | |
| 236 | class TurtleShell(cmd.Cmd): |
| 237 | intro = 'Welcome to the turtle shell. Type help or ? to list commands.\n' |
| 238 | prompt = '(turtle) ' |
| 239 | file = None |
| 240 | |
| 241 | # ----- basic turtle commands ----- |
| 242 | def do_forward(self, arg): |
| 243 | 'Move the turtle forward by the specified distance: FORWARD 10' |
| 244 | forward(*parse(arg)) |
| 245 | def do_right(self, arg): |
| 246 | 'Turn turtle right by given number of degrees: RIGHT 20' |
| 247 | right(*parse(arg)) |
| 248 | def do_left(self, arg): |
| 249 | 'Turn turtle left by given number of degrees: LEFT 90' |
Ezio Melotti | 4165bfb | 2011-09-10 10:06:01 +0300 | [diff] [blame] | 250 | left(*parse(arg)) |
Raymond Hettinger | bd889e8 | 2010-09-09 01:40:50 +0000 | [diff] [blame] | 251 | def do_goto(self, arg): |
| 252 | 'Move turtle to an absolute position with changing orientation. GOTO 100 200' |
| 253 | goto(*parse(arg)) |
| 254 | def do_home(self, arg): |
| 255 | 'Return turtle to the home postion: HOME' |
| 256 | home() |
| 257 | def do_circle(self, arg): |
| 258 | 'Draw circle with given radius an options extent and steps: CIRCLE 50' |
| 259 | circle(*parse(arg)) |
| 260 | def do_position(self, arg): |
| 261 | 'Print the current turle position: POSITION' |
| 262 | print('Current position is %d %d\n' % position()) |
| 263 | def do_heading(self, arg): |
| 264 | 'Print the current turle heading in degrees: HEADING' |
| 265 | print('Current heading is %d\n' % (heading(),)) |
| 266 | def do_color(self, arg): |
| 267 | 'Set the color: COLOR BLUE' |
| 268 | color(arg.lower()) |
| 269 | def do_undo(self, arg): |
| 270 | 'Undo (repeatedly) the last turtle action(s): UNDO' |
| 271 | def do_reset(self, arg): |
| 272 | 'Clear the screen and return turtle to center: RESET' |
| 273 | reset() |
| 274 | def do_bye(self, arg): |
| 275 | 'Stop recording, close the turtle window, and exit: BYE' |
| 276 | print('Thank you for using Turtle') |
| 277 | self.close() |
| 278 | bye() |
| 279 | sys.exit(0) |
| 280 | |
| 281 | # ----- record and playback ----- |
| 282 | def do_record(self, arg): |
| 283 | 'Save future commands to filename: RECORD rose.cmd' |
| 284 | self.file = open(arg, 'w') |
| 285 | def do_playback(self, arg): |
| 286 | 'Playback commands from a file: PLAYBACK rose.cmd' |
| 287 | self.close() |
Éric Araujo | a3dd56b | 2011-03-11 17:42:48 +0100 | [diff] [blame] | 288 | with open(arg) as f: |
| 289 | self.cmdqueue.extend(f.read().splitlines()) |
Raymond Hettinger | bd889e8 | 2010-09-09 01:40:50 +0000 | [diff] [blame] | 290 | def precmd(self, line): |
| 291 | line = line.lower() |
| 292 | if self.file and 'playback' not in line: |
| 293 | print(line, file=self.file) |
| 294 | return line |
| 295 | def close(self): |
| 296 | if self.file: |
| 297 | self.file.close() |
| 298 | self.file = None |
| 299 | |
| 300 | def parse(arg): |
| 301 | 'Convert a series of zero or more numbers to an argument tuple' |
| 302 | return tuple(map(int, arg.split())) |
| 303 | |
| 304 | if __name__ == '__main__': |
| 305 | TurtleShell().cmdloop() |
| 306 | |
| 307 | |
| 308 | Here is a sample session with the turtle shell showing the help functions, using |
| 309 | blank lines to repeat commands, and the simple record and playback facility:: |
| 310 | |
| 311 | Welcome to the turtle shell. Type help or ? to list commands. |
| 312 | |
| 313 | (turtle) ? |
| 314 | |
| 315 | Documented commands (type help <topic>): |
| 316 | ======================================== |
| 317 | bye color goto home playback record right |
| 318 | circle forward heading left position reset undo |
| 319 | |
Raymond Hettinger | bd889e8 | 2010-09-09 01:40:50 +0000 | [diff] [blame] | 320 | (turtle) help forward |
| 321 | Move the turtle forward by the specified distance: FORWARD 10 |
| 322 | (turtle) record spiral.cmd |
| 323 | (turtle) position |
| 324 | Current position is 0 0 |
| 325 | |
| 326 | (turtle) heading |
| 327 | Current heading is 0 |
| 328 | |
| 329 | (turtle) reset |
| 330 | (turtle) circle 20 |
| 331 | (turtle) right 30 |
| 332 | (turtle) circle 40 |
| 333 | (turtle) right 30 |
| 334 | (turtle) circle 60 |
| 335 | (turtle) right 30 |
| 336 | (turtle) circle 80 |
| 337 | (turtle) right 30 |
| 338 | (turtle) circle 100 |
| 339 | (turtle) right 30 |
| 340 | (turtle) circle 120 |
| 341 | (turtle) right 30 |
| 342 | (turtle) circle 120 |
| 343 | (turtle) heading |
| 344 | Current heading is 180 |
| 345 | |
| 346 | (turtle) forward 100 |
| 347 | (turtle) |
| 348 | (turtle) right 90 |
| 349 | (turtle) forward 100 |
| 350 | (turtle) |
| 351 | (turtle) right 90 |
| 352 | (turtle) forward 400 |
| 353 | (turtle) right 90 |
| 354 | (turtle) forward 500 |
| 355 | (turtle) right 90 |
| 356 | (turtle) forward 400 |
| 357 | (turtle) right 90 |
| 358 | (turtle) forward 300 |
| 359 | (turtle) playback spiral.cmd |
| 360 | Current position is 0 0 |
| 361 | |
| 362 | Current heading is 0 |
| 363 | |
| 364 | Current heading is 180 |
| 365 | |
| 366 | (turtle) bye |
| 367 | Thank you for using Turtle |
| 368 | |