blob: 53d62c5c946c32e7e829c72efdcf3b4b44495cdd [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.
6.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
7
8
9The :class:`Cmd` class provides a simple framework for writing line-oriented
10command interpreters. These are often useful for test harnesses, administrative
11tools, and prototypes that will later be wrapped in a more sophisticated
12interface.
13
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000014.. seealso::
15
16 Latest version of the :source:`cmd module Python source code <Lib/cmd.py>`
Georg Brandl116aa622007-08-15 14:28:22 +000017
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
54 prompt (this overrides the :attr:`intro` class member).
55
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
152Instances of :class:`Cmd` subclasses have some public instance variables:
153
154
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
170.. attribute:: Cmd.intro
171
172 A string to issue as an intro or banner. May be overridden by giving the
173 :meth:`cmdloop` method an argument.
174
175
176.. attribute:: Cmd.doc_header
177
178 The header to issue if the help output has a section for documented commands.
179
180
181.. attribute:: Cmd.misc_header
182
183 The header to issue if the help output has a section for miscellaneous help
184 topics (that is, there are :meth:`help_\*` methods without corresponding
185 :meth:`do_\*` methods).
186
187
188.. attribute:: Cmd.undoc_header
189
190 The header to issue if the help output has a section for undocumented commands
191 (that is, there are :meth:`do_\*` methods without corresponding :meth:`help_\*`
192 methods).
193
194
195.. attribute:: Cmd.ruler
196
197 The character used to draw separator lines under the help-message headers. If
198 empty, no ruler line is drawn. It defaults to ``'='``.
199
200
201.. attribute:: Cmd.use_rawinput
202
203 A flag, defaulting to true. If true, :meth:`cmdloop` uses :func:`input` to
204 display a prompt and read the next command; if false, :meth:`sys.stdout.write`
205 and :meth:`sys.stdin.readline` are used. (This means that by importing
206 :mod:`readline`, on systems that support it, the interpreter will automatically
207 support :program:`Emacs`\ -like line editing and command-history keystrokes.)
208
Raymond Hettingerbd889e82010-09-09 01:40:50 +0000209Cmd Example
Alexander Belopolskyf0a0d142010-10-27 03:06:43 +0000210-----------
Raymond Hettingerbd889e82010-09-09 01:40:50 +0000211
212.. sectionauthor:: Raymond Hettinger <python at rcn dot com>
213
214The :mod:`cmd` module is mainly useful for building custom shells that let a
215user work with a program interactively.
216
217This section presents a simple example of how to build a shell around a few of
218the commands in the :mod:`turtle` module.
219
220Basic turtle commands such as :meth:`~turtle.forward` are added to a
221:class:`Cmd` subclass with method named :meth:`do_forward`. The argument is
222converted to a number and dispatched to the turtle module. The docstring is
223used in the help utility provided by the shell.
224
225The example also includes a basic record and playback facility implemented with
226the :meth:`~Cmd.precmd` method which is responsible for converting the input to
227lowercase and writing the commands to a file. The :meth:`do_playback` method
228reads the file and adds the recorded commands to the :attr:`cmdqueue` for
229immediate playback::
230
231 import cmd, sys
232 from turtle import *
233
234 class TurtleShell(cmd.Cmd):
235 intro = 'Welcome to the turtle shell. Type help or ? to list commands.\n'
236 prompt = '(turtle) '
237 file = None
238
239 # ----- basic turtle commands -----
240 def do_forward(self, arg):
241 'Move the turtle forward by the specified distance: FORWARD 10'
242 forward(*parse(arg))
243 def do_right(self, arg):
244 'Turn turtle right by given number of degrees: RIGHT 20'
245 right(*parse(arg))
246 def do_left(self, arg):
247 'Turn turtle left by given number of degrees: LEFT 90'
248 right(*parse(arg))
249 def do_goto(self, arg):
250 'Move turtle to an absolute position with changing orientation. GOTO 100 200'
251 goto(*parse(arg))
252 def do_home(self, arg):
253 'Return turtle to the home postion: HOME'
254 home()
255 def do_circle(self, arg):
256 'Draw circle with given radius an options extent and steps: CIRCLE 50'
257 circle(*parse(arg))
258 def do_position(self, arg):
259 'Print the current turle position: POSITION'
260 print('Current position is %d %d\n' % position())
261 def do_heading(self, arg):
262 'Print the current turle heading in degrees: HEADING'
263 print('Current heading is %d\n' % (heading(),))
264 def do_color(self, arg):
265 'Set the color: COLOR BLUE'
266 color(arg.lower())
267 def do_undo(self, arg):
268 'Undo (repeatedly) the last turtle action(s): UNDO'
269 def do_reset(self, arg):
270 'Clear the screen and return turtle to center: RESET'
271 reset()
272 def do_bye(self, arg):
273 'Stop recording, close the turtle window, and exit: BYE'
274 print('Thank you for using Turtle')
275 self.close()
276 bye()
277 sys.exit(0)
278
279 # ----- record and playback -----
280 def do_record(self, arg):
281 'Save future commands to filename: RECORD rose.cmd'
282 self.file = open(arg, 'w')
283 def do_playback(self, arg):
284 'Playback commands from a file: PLAYBACK rose.cmd'
285 self.close()
286 cmds = open(arg).read().splitlines()
287 self.cmdqueue.extend(cmds)
288 def precmd(self, line):
289 line = line.lower()
290 if self.file and 'playback' not in line:
291 print(line, file=self.file)
292 return line
293 def close(self):
294 if self.file:
295 self.file.close()
296 self.file = None
297
298 def parse(arg):
299 'Convert a series of zero or more numbers to an argument tuple'
300 return tuple(map(int, arg.split()))
301
302 if __name__ == '__main__':
303 TurtleShell().cmdloop()
304
305
306Here is a sample session with the turtle shell showing the help functions, using
307blank lines to repeat commands, and the simple record and playback facility::
308
309 Welcome to the turtle shell. Type help or ? to list commands.
310
311 (turtle) ?
312
313 Documented commands (type help <topic>):
314 ========================================
315 bye color goto home playback record right
316 circle forward heading left position reset undo
317
Raymond Hettingerbd889e82010-09-09 01:40:50 +0000318 (turtle) help forward
319 Move the turtle forward by the specified distance: FORWARD 10
320 (turtle) record spiral.cmd
321 (turtle) position
322 Current position is 0 0
323
324 (turtle) heading
325 Current heading is 0
326
327 (turtle) reset
328 (turtle) circle 20
329 (turtle) right 30
330 (turtle) circle 40
331 (turtle) right 30
332 (turtle) circle 60
333 (turtle) right 30
334 (turtle) circle 80
335 (turtle) right 30
336 (turtle) circle 100
337 (turtle) right 30
338 (turtle) circle 120
339 (turtle) right 30
340 (turtle) circle 120
341 (turtle) heading
342 Current heading is 180
343
344 (turtle) forward 100
345 (turtle)
346 (turtle) right 90
347 (turtle) forward 100
348 (turtle)
349 (turtle) right 90
350 (turtle) forward 400
351 (turtle) right 90
352 (turtle) forward 500
353 (turtle) right 90
354 (turtle) forward 400
355 (turtle) right 90
356 (turtle) forward 300
357 (turtle) playback spiral.cmd
358 Current position is 0 0
359
360 Current heading is 0
361
362 Current heading is 180
363
364 (turtle) bye
365 Thank you for using Turtle
366