1 """A generic class to build line-oriented command interpreters.
3 Interpreters constructed with this class obey the following conventions:
5 1. End of file on input is processed as the command 'EOF'.
6 2. A command is parsed out of each line by collecting the prefix composed
7 of characters in the identchars member.
8 3. A command `foo' is dispatched to a method 'do_foo()'; the do_ method
9 is passed a single argument consisting of the remainder of the line.
10 4. Typing an empty line repeats the last command. (Actually, it calls the
11 method `emptyline', which may be overridden in a subclass.)
12 5. There is a predefined `help' method. Given an argument `topic', it
13 calls the command `help_topic'. With no arguments, it lists all topics
14 with defined help_ functions, broken into up to three topics; documented
15 commands, miscellaneous help topics, and undocumented commands.
16 6. The command '?' is a synonym for `help'. The command '!' is a synonym
17 for `shell', if a do_shell method exists.
18 7. If completion is enabled, completing commands will be done automatically,
19 and completing of commands args is done by calling complete_foo() with
20 arguments text, line, begidx, endidx. text is string we are matching
21 against, all returned matches must begin with it. line is the current
22 input line (lstripped), begidx and endidx are the beginning and end
23 indexes of the text being matched, which could be used to provide
24 different completion depending upon which position the argument is in.
26 The `default' method may be overridden to intercept commands for which there
29 The `completedefault' method may be overridden to intercept completions for
30 commands that have no complete_ method.
32 The data member `self.ruler' sets the character used to draw separator lines
33 in the help messages. If empty, no ruler line is drawn. It defaults to "=".
35 If the value of `self.intro' is nonempty when the cmdloop method is called,
36 it is printed out on interpreter startup. This value may be overridden
37 via an optional argument to the cmdloop() method.
39 The data members `self.doc_header', `self.misc_header', and
40 `self.undoc_header' set the headers used for the help function's
41 listings of documented functions, miscellaneous topics, and undocumented
42 functions respectively.
44 These interpreters use raw_input; thus, if the readline module is loaded,
45 they automatically support Emacs-like command history and editing features.
53 IDENTCHARS
= string
.ascii_letters
+ string
.digits
+ '_'
56 """A simple framework for writing line-oriented command interpreters.
58 These are often useful for test harnesses, administrative tools, and
59 prototypes that will later be wrapped in a more sophisticated interface.
61 A Cmd instance or subclass instance is a line-oriented interpreter
62 framework. There is no good reason to instantiate Cmd itself; rather,
63 it's useful as a superclass of an interpreter class you define yourself
64 in order to inherit Cmd's methods and encapsulate action methods.
68 identchars
= IDENTCHARS
73 doc_header
= "Documented commands (type help <topic>):"
74 misc_header
= "Miscellaneous help topics:"
75 undoc_header
= "Undocumented commands:"
76 nohelp
= "*** No help on %s"
79 def __init__(self
, completekey
='tab', stdin
=None, stdout
=None):
80 """Instantiate a line-oriented interpreter framework.
82 The optional argument 'completekey' is the readline name of a
83 completion key; it defaults to the Tab key. If completekey is
84 not None and the readline module is available, command completion
85 is done automatically. The optional arguments stdin and stdout
86 specify alternate input and output file objects; if not specified,
87 sys.stdin and sys.stdout are used.
94 self
.stdin
= sys
.stdin
95 if stdout
is not None:
98 self
.stdout
= sys
.stdout
100 self
.completekey
= completekey
102 def cmdloop(self
, intro
=None):
103 """Repeatedly issue a prompt, accept input, parse an initial prefix
104 off the received input, and dispatch to action methods, passing them
105 the remainder of the line as argument.
110 if intro
is not None:
113 self
.stdout
.write(str(self
.intro
)+"\n")
117 line
= self
.cmdqueue
.pop(0)
119 if self
.use_rawinput
:
121 line
= raw_input(self
.prompt
)
125 self
.stdout
.write(self
.prompt
)
127 line
= self
.stdin
.readline()
131 line
= line
[:-1] # chop \n
132 line
= self
.precmd(line
)
133 stop
= self
.onecmd(line
)
134 stop
= self
.postcmd(stop
, line
)
137 def precmd(self
, line
):
138 """Hook method executed just before the command line is
139 interpreted, but after the input prompt is generated and issued.
144 def postcmd(self
, stop
, line
):
145 """Hook method executed just after a command dispatch is finished."""
149 """Hook method executed once when the cmdloop() method is called."""
153 self
.old_completer
= readline
.get_completer()
154 readline
.set_completer(self
.complete
)
155 readline
.parse_and_bind(self
.completekey
+": complete")
160 """Hook method executed once when the cmdloop() method is about to
167 readline
.set_completer(self
.old_completer
)
171 def parseline(self
, line
):
174 return None, None, line
176 line
= 'help ' + line
[1:]
178 if hasattr(self
, 'do_shell'):
179 line
= 'shell ' + line
[1:]
181 return None, None, line
183 while i
< n
and line
[i
] in self
.identchars
: i
= i
+1
184 cmd
, arg
= line
[:i
], line
[i
:].strip()
185 return cmd
, arg
, line
187 def onecmd(self
, line
):
188 """Interpret the argument as though it had been typed in response
191 This may be overridden, but should not normally need to be;
192 see the precmd() and postcmd() methods for useful execution hooks.
193 The return value is a flag indicating whether interpretation of
194 commands by the interpreter should stop.
197 cmd
, arg
, line
= self
.parseline(line
)
199 return self
.emptyline()
201 return self
.default(line
)
204 return self
.default(line
)
207 func
= getattr(self
, 'do_' + cmd
)
208 except AttributeError:
209 return self
.default(line
)
213 """Called when an empty line is entered in response to the prompt.
215 If this method is not overridden, it repeats the last nonempty
220 return self
.onecmd(self
.lastcmd
)
222 def default(self
, line
):
223 """Called on an input line when the command prefix is not recognized.
225 If this method is not overridden, it prints an error message and
229 self
.stdout
.write('*** Unknown syntax: %s\n'%line
)
231 def completedefault(self
, *ignored
):
232 """Method called to complete an input line when no command-specific
233 complete_*() method is available.
235 By default, it returns an empty list.
240 def completenames(self
, text
, *ignored
):
242 return [a
[3:] for a
in self
.get_names() if a
.startswith(dotext
)]
244 def complete(self
, text
, state
):
245 """Return the next possible completion for 'text'.
247 If a command has not been entered, then complete against command list.
248 Otherwise try to call complete_<command> to get list of completions.
252 origline
= readline
.get_line_buffer()
253 line
= origline
.lstrip()
254 stripped
= len(origline
) - len(line
)
255 begidx
= readline
.get_begidx() - stripped
256 endidx
= readline
.get_endidx() - stripped
258 cmd
, args
, foo
= self
.parseline(line
)
260 compfunc
= self
.completedefault
263 compfunc
= getattr(self
, 'complete_' + cmd
)
264 except AttributeError:
265 compfunc
= self
.completedefault
267 compfunc
= self
.completenames
268 self
.completion_matches
= compfunc(text
, line
, begidx
, endidx
)
270 return self
.completion_matches
[state
]
275 # Inheritance says we have to look in class and
276 # base classes; order is not important.
278 classes
= [self
.__class
__]
280 aclass
= classes
.pop(0)
282 classes
= classes
+ list(aclass
.__bases
__)
283 names
= names
+ dir(aclass
)
286 def complete_help(self
, *args
):
287 return self
.completenames(*args
)
289 def do_help(self
, arg
):
291 # XXX check arg syntax
293 func
= getattr(self
, 'help_' + arg
)
294 except AttributeError:
296 doc
=getattr(self
, 'do_' + arg
).__doc
__
298 self
.stdout
.write("%s\n"%str
(doc
))
300 except AttributeError:
302 self
.stdout
.write("%s\n"%str
(self
.nohelp
% (arg
,)))
306 names
= self
.get_names()
311 if name
[:5] == 'help_':
314 # There can be duplicates if routines overridden
317 if name
[:3] == 'do_':
325 elif getattr(self
, name
).__doc
__:
328 cmds_undoc
.append(cmd
)
329 self
.stdout
.write("%s\n"%str
(self
.doc_leader
))
330 self
.print_topics(self
.doc_header
, cmds_doc
, 15,80)
331 self
.print_topics(self
.misc_header
, help.keys(),15,80)
332 self
.print_topics(self
.undoc_header
, cmds_undoc
, 15,80)
334 def print_topics(self
, header
, cmds
, cmdlen
, maxcol
):
336 self
.stdout
.write("%s\n"%str
(header
))
338 self
.stdout
.write("%s\n"%str
(self
.ruler
* len(header
)))
339 self
.columnize(cmds
, maxcol
-1)
340 self
.stdout
.write("\n")
342 def columnize(self
, list, displaywidth
=80):
343 """Display a list of strings as a compact set of columns.
345 Each column is only as wide as necessary.
346 Columns are separated by two spaces (one was not legible enough).
349 self
.stdout
.write("<empty>\n")
351 nonstrings
= [i
for i
in range(len(list))
352 if not isinstance(list[i
], str)]
354 raise TypeError, ("list[i] not a string for i in %s" %
355 ", ".join(map(str, nonstrings
)))
358 self
.stdout
.write('%s\n'%str
(list[0]))
360 # Try every row count from 1 upwards
361 for nrows
in range(1, len(list)):
362 ncols
= (size
+nrows
-1) // nrows
365 for col
in range(ncols
):
367 for row
in range(nrows
):
372 colwidth
= max(colwidth
, len(x
))
373 colwidths
.append(colwidth
)
374 totwidth
+= colwidth
+ 2
375 if totwidth
> displaywidth
:
377 if totwidth
<= displaywidth
:
383 for row
in range(nrows
):
385 for col
in range(ncols
):
392 while texts
and not texts
[-1]:
394 for col
in range(len(texts
)):
395 texts
[col
] = texts
[col
].ljust(colwidths
[col
])
396 self
.stdout
.write("%s\n"%str
(" ".join(texts
)))