blob: 0bb0c0372314e87377cf88c772b96e1f063cc459 [file] [log] [blame]
Guido van Rossum4acc25b2000-02-02 15:10:15 +00001"""A generic class to build line-oriented command interpreters.
2
3Interpreters constructed with this class obey the following conventions:
4
51. End of file on input is processed as the command 'EOF'.
62. A command is parsed out of each line by collecting the prefix composed
7 of characters in the identchars member.
83. 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.
104. Typing an empty line repeats the last command. (Actually, it calls the
11 method `emptyline', which may be overridden in a subclass.)
125. 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.
166. The command '?' is a synonym for `help'. The command '!' is a synonym
17 for `shell', if a do_shell method exists.
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000187. 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
Tim Petersab9ba272001-08-09 21:40:30 +000023 indexes of the text being matched, which could be used to provide
Martin v. Löwis66b6e192001-07-28 14:44:03 +000024 different completion depending upon which position the argument is in.
Guido van Rossum4acc25b2000-02-02 15:10:15 +000025
26The `default' method may be overridden to intercept commands for which there
27is no do_ method.
28
Martin v. Löwis66b6e192001-07-28 14:44:03 +000029The `completedefault' method may be overridden to intercept completions for
Tim Petersab9ba272001-08-09 21:40:30 +000030commands that have no complete_ method.
Martin v. Löwis66b6e192001-07-28 14:44:03 +000031
Guido van Rossum4acc25b2000-02-02 15:10:15 +000032The data member `self.ruler' sets the character used to draw separator lines
33in the help messages. If empty, no ruler line is drawn. It defaults to "=".
34
35If the value of `self.intro' is nonempty when the cmdloop method is called,
36it is printed out on interpreter startup. This value may be overridden
37via an optional argument to the cmdloop() method.
38
39The data members `self.doc_header', `self.misc_header', and
40`self.undoc_header' set the headers used for the help function's
41listings of documented functions, miscellaneous topics, and undocumented
42functions respectively.
43
44These interpreters use raw_input; thus, if the readline module is loaded,
45they automatically support Emacs-like command history and editing features.
46"""
Guido van Rossumb53e6781992-01-24 01:12:17 +000047
Anthony Baxter983b0082003-02-06 01:45:11 +000048import string
Guido van Rossumb53e6781992-01-24 01:12:17 +000049
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000050__all__ = ["Cmd"]
51
Guido van Rossumb53e6781992-01-24 01:12:17 +000052PROMPT = '(Cmd) '
Fred Drake79e75e12001-07-20 19:05:50 +000053IDENTCHARS = string.ascii_letters + string.digits + '_'
Guido van Rossumb53e6781992-01-24 01:12:17 +000054
55class Cmd:
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000056 """A simple framework for writing line-oriented command interpreters.
57
58 These are often useful for test harnesses, administrative tools, and
59 prototypes that will later be wrapped in a more sophisticated interface.
60
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.
65
66 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +000067 prompt = PROMPT
68 identchars = IDENTCHARS
69 ruler = '='
70 lastcmd = ''
Guido van Rossum4acc25b2000-02-02 15:10:15 +000071 intro = None
72 doc_leader = ""
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"
Guido van Rossumbfb91842001-03-22 21:59:20 +000077 use_rawinput = 1
Guido van Rossum9b3bc711993-06-20 21:02:22 +000078
Anthony Baxter983b0082003-02-06 01:45:11 +000079 def __init__(self, completekey='tab', stdin=None, stdout=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000080 """Instantiate a line-oriented interpreter framework.
81
Tim Petersf2715e02003-02-19 02:35:07 +000082 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
Anthony Baxter983b0082003-02-06 01:45:11 +000085 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.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000088
89 """
Anthony Baxter983b0082003-02-06 01:45:11 +000090 import sys
91 if stdin is not None:
92 self.stdin = stdin
93 else:
94 self.stdin = sys.stdin
95 if stdout is not None:
96 self.stdout = stdout
97 else:
98 self.stdout = sys.stdout
Guido van Rossum87fec222003-01-13 21:18:54 +000099 self.cmdqueue = []
Michael W. Hudson35a92ce2003-02-03 11:04:27 +0000100 self.completekey = completekey
Guido van Rossum030eb111998-07-01 22:53:04 +0000101
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000102 def cmdloop(self, intro=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000103 """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.
106
107 """
108
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000109 self.preloop()
Fred Drake8152d322000-12-12 23:20:45 +0000110 if intro is not None:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000111 self.intro = intro
112 if self.intro:
Anthony Baxter983b0082003-02-06 01:45:11 +0000113 self.stdout.write(str(self.intro)+"\n")
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000114 stop = None
115 while not stop:
116 if self.cmdqueue:
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000117 line = self.cmdqueue.pop(0)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000118 else:
Guido van Rossumbfb91842001-03-22 21:59:20 +0000119 if self.use_rawinput:
120 try:
121 line = raw_input(self.prompt)
122 except EOFError:
123 line = 'EOF'
124 else:
Anthony Baxter983b0082003-02-06 01:45:11 +0000125 self.stdout.write(self.prompt)
126 self.stdout.flush()
127 line = self.stdin.readline()
Guido van Rossumbfb91842001-03-22 21:59:20 +0000128 if not len(line):
129 line = 'EOF'
130 else:
131 line = line[:-1] # chop \n
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000132 line = self.precmd(line)
133 stop = self.onecmd(line)
134 stop = self.postcmd(stop, line)
135 self.postloop()
Guido van Rossum80884071998-06-29 17:58:55 +0000136
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000137 def precmd(self, line):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000138 """Hook method executed just before the command line is
139 interpreted, but after the input prompt is generated and issued.
140
141 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000142 return line
Guido van Rossum80884071998-06-29 17:58:55 +0000143
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000144 def postcmd(self, stop, line):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000145 """Hook method executed just after a command dispatch is finished."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000146 return stop
Guido van Rossum80884071998-06-29 17:58:55 +0000147
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000148 def preloop(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000149 """Hook method executed once when the cmdloop() method is called."""
Michael W. Hudson35a92ce2003-02-03 11:04:27 +0000150 if self.completekey:
151 try:
152 import readline
153 self.old_completer = readline.get_completer()
154 readline.set_completer(self.complete)
155 readline.parse_and_bind(self.completekey+": complete")
156 except ImportError:
157 pass
Guido van Rossum80884071998-06-29 17:58:55 +0000158
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000159 def postloop(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000160 """Hook method executed once when the cmdloop() method is about to
161 return.
162
163 """
Michael W. Hudson35a92ce2003-02-03 11:04:27 +0000164 if self.completekey:
165 try:
166 import readline
167 readline.set_completer(self.old_completer)
168 except ImportError:
169 pass
Guido van Rossumb53e6781992-01-24 01:12:17 +0000170
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000171 def parseline(self, line):
Andrew M. Kuchling7cebbf32003-10-22 14:38:54 +0000172 """Parse the line into a command name and a string containing
173 the arguments. Returns a tuple containing (command, args, line).
174 'command' and 'args' may be None if the line couldn't be parsed.
175 """
Eric S. Raymond20e44232001-02-09 04:52:11 +0000176 line = line.strip()
Eric S. Raymond5f1b2702000-07-11 13:03:55 +0000177 if not line:
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000178 return None, None, line
Eric S. Raymond5f1b2702000-07-11 13:03:55 +0000179 elif line[0] == '?':
180 line = 'help ' + line[1:]
181 elif line[0] == '!':
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000182 if hasattr(self, 'do_shell'):
Eric S. Raymond5f1b2702000-07-11 13:03:55 +0000183 line = 'shell ' + line[1:]
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000184 else:
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000185 return None, None, line
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000186 i, n = 0, len(line)
187 while i < n and line[i] in self.identchars: i = i+1
Eric S. Raymond20e44232001-02-09 04:52:11 +0000188 cmd, arg = line[:i], line[i:].strip()
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000189 return cmd, arg, line
Tim Petersab9ba272001-08-09 21:40:30 +0000190
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000191 def onecmd(self, line):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000192 """Interpret the argument as though it had been typed in response
193 to the prompt.
194
195 This may be overridden, but should not normally need to be;
196 see the precmd() and postcmd() methods for useful execution hooks.
197 The return value is a flag indicating whether interpretation of
198 commands by the interpreter should stop.
199
200 """
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000201 cmd, arg, line = self.parseline(line)
202 if not line:
203 return self.emptyline()
204 if cmd is None:
205 return self.default(line)
206 self.lastcmd = line
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000207 if cmd == '':
208 return self.default(line)
209 else:
210 try:
211 func = getattr(self, 'do_' + cmd)
212 except AttributeError:
213 return self.default(line)
214 return func(arg)
Guido van Rossumb53e6781992-01-24 01:12:17 +0000215
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000216 def emptyline(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000217 """Called when an empty line is entered in response to the prompt.
218
219 If this method is not overridden, it repeats the last nonempty
220 command entered.
221
222 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000223 if self.lastcmd:
224 return self.onecmd(self.lastcmd)
Guido van Rossum80884071998-06-29 17:58:55 +0000225
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000226 def default(self, line):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000227 """Called on an input line when the command prefix is not recognized.
228
229 If this method is not overridden, it prints an error message and
230 returns.
231
232 """
Anthony Baxter983b0082003-02-06 01:45:11 +0000233 self.stdout.write('*** Unknown syntax: %s\n'%line)
Guido van Rossumb53e6781992-01-24 01:12:17 +0000234
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000235 def completedefault(self, *ignored):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000236 """Method called to complete an input line when no command-specific
237 complete_*() method is available.
238
239 By default, it returns an empty list.
240
241 """
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000242 return []
243
244 def completenames(self, text, *ignored):
245 dotext = 'do_'+text
246 return [a[3:] for a in self.get_names() if a.startswith(dotext)]
247
248 def complete(self, text, state):
249 """Return the next possible completion for 'text'.
250
251 If a command has not been entered, then complete against command list.
252 Otherwise try to call complete_<command> to get list of completions.
253 """
254 if state == 0:
255 import readline
256 origline = readline.get_line_buffer()
257 line = origline.lstrip()
258 stripped = len(origline) - len(line)
259 begidx = readline.get_begidx() - stripped
260 endidx = readline.get_endidx() - stripped
261 if begidx>0:
262 cmd, args, foo = self.parseline(line)
263 if cmd == '':
264 compfunc = self.completedefault
265 else:
266 try:
267 compfunc = getattr(self, 'complete_' + cmd)
268 except AttributeError:
269 compfunc = self.completedefault
270 else:
271 compfunc = self.completenames
272 self.completion_matches = compfunc(text, line, begidx, endidx)
273 try:
274 return self.completion_matches[state]
275 except IndexError:
276 return None
Tim Petersab9ba272001-08-09 21:40:30 +0000277
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000278 def get_names(self):
279 # Inheritance says we have to look in class and
280 # base classes; order is not important.
281 names = []
282 classes = [self.__class__]
283 while classes:
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000284 aclass = classes.pop(0)
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000285 if aclass.__bases__:
286 classes = classes + list(aclass.__bases__)
287 names = names + dir(aclass)
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000288 return names
289
290 def complete_help(self, *args):
291 return self.completenames(*args)
292
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000293 def do_help(self, arg):
294 if arg:
295 # XXX check arg syntax
296 try:
297 func = getattr(self, 'help_' + arg)
Skip Montanaro1ce00732002-03-24 16:34:21 +0000298 except AttributeError:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000299 try:
300 doc=getattr(self, 'do_' + arg).__doc__
301 if doc:
Anthony Baxter983b0082003-02-06 01:45:11 +0000302 self.stdout.write("%s\n"%str(doc))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000303 return
Skip Montanaro1ce00732002-03-24 16:34:21 +0000304 except AttributeError:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000305 pass
Anthony Baxter983b0082003-02-06 01:45:11 +0000306 self.stdout.write("%s\n"%str(self.nohelp % (arg,)))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000307 return
308 func()
309 else:
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000310 names = self.get_names()
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000311 cmds_doc = []
312 cmds_undoc = []
313 help = {}
314 for name in names:
315 if name[:5] == 'help_':
316 help[name[5:]]=1
317 names.sort()
318 # There can be duplicates if routines overridden
319 prevname = ''
320 for name in names:
321 if name[:3] == 'do_':
322 if name == prevname:
323 continue
324 prevname = name
325 cmd=name[3:]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000326 if cmd in help:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000327 cmds_doc.append(cmd)
328 del help[cmd]
329 elif getattr(self, name).__doc__:
330 cmds_doc.append(cmd)
331 else:
332 cmds_undoc.append(cmd)
Anthony Baxter983b0082003-02-06 01:45:11 +0000333 self.stdout.write("%s\n"%str(self.doc_leader))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000334 self.print_topics(self.doc_header, cmds_doc, 15,80)
335 self.print_topics(self.misc_header, help.keys(),15,80)
336 self.print_topics(self.undoc_header, cmds_undoc, 15,80)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000337
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000338 def print_topics(self, header, cmds, cmdlen, maxcol):
339 if cmds:
Anthony Baxter983b0082003-02-06 01:45:11 +0000340 self.stdout.write("%s\n"%str(header))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000341 if self.ruler:
Anthony Baxter983b0082003-02-06 01:45:11 +0000342 self.stdout.write("%s\n"%str(self.ruler * len(header)))
Guido van Rossumc706c282002-12-02 13:08:53 +0000343 self.columnize(cmds, maxcol-1)
Anthony Baxter983b0082003-02-06 01:45:11 +0000344 self.stdout.write("\n")
Guido van Rossumc706c282002-12-02 13:08:53 +0000345
346 def columnize(self, list, displaywidth=80):
347 """Display a list of strings as a compact set of columns.
348
349 Each column is only as wide as necessary.
350 Columns are separated by two spaces (one was not legible enough).
351 """
352 if not list:
Anthony Baxter983b0082003-02-06 01:45:11 +0000353 self.stdout.write("<empty>\n")
Guido van Rossumc706c282002-12-02 13:08:53 +0000354 return
355 nonstrings = [i for i in range(len(list))
356 if not isinstance(list[i], str)]
357 if nonstrings:
358 raise TypeError, ("list[i] not a string for i in %s" %
359 ", ".join(map(str, nonstrings)))
360 size = len(list)
361 if size == 1:
Anthony Baxter983b0082003-02-06 01:45:11 +0000362 self.stdout.write('%s\n'%str(list[0]))
Guido van Rossumc706c282002-12-02 13:08:53 +0000363 return
364 # Try every row count from 1 upwards
365 for nrows in range(1, len(list)):
366 ncols = (size+nrows-1) // nrows
367 colwidths = []
368 totwidth = -2
369 for col in range(ncols):
370 colwidth = 0
371 for row in range(nrows):
372 i = row + nrows*col
373 if i >= size:
374 break
375 x = list[i]
376 colwidth = max(colwidth, len(x))
377 colwidths.append(colwidth)
378 totwidth += colwidth + 2
379 if totwidth > displaywidth:
380 break
381 if totwidth <= displaywidth:
382 break
383 else:
384 nrows = len(list)
385 ncols = 1
386 colwidths = [0]
387 for row in range(nrows):
388 texts = []
389 for col in range(ncols):
390 i = row + nrows*col
391 if i >= size:
392 x = ""
393 else:
394 x = list[i]
395 texts.append(x)
396 while texts and not texts[-1]:
397 del texts[-1]
398 for col in range(len(texts)):
399 texts[col] = texts[col].ljust(colwidths[col])
Anthony Baxter983b0082003-02-06 01:45:11 +0000400 self.stdout.write("%s\n"%str(" ".join(texts)))