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