blob: 23dc5b2fb2612c33750f187ecb80ce9559d01faf [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.
Guido van Rossum4acc25b2000-02-02 15:10:15 +000043"""
Guido van Rossumb53e6781992-01-24 01:12:17 +000044
Neal Norwitzce96f692006-03-17 06:49:51 +000045import string, sys
Guido van Rossumb53e6781992-01-24 01:12:17 +000046
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000047__all__ = ["Cmd"]
48
Guido van Rossumb53e6781992-01-24 01:12:17 +000049PROMPT = '(Cmd) '
Fred Drake79e75e12001-07-20 19:05:50 +000050IDENTCHARS = string.ascii_letters + string.digits + '_'
Guido van Rossumb53e6781992-01-24 01:12:17 +000051
Neal Norwitzce96f692006-03-17 06:49:51 +000052def raw_input(prompt):
53 sys.stdout.write(prompt)
54 sys.stdout.flush()
55 return sys.stdin.readline()
56
Guido van Rossumb53e6781992-01-24 01:12:17 +000057class Cmd:
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000058 """A simple framework for writing line-oriented command interpreters.
59
60 These are often useful for test harnesses, administrative tools, and
61 prototypes that will later be wrapped in a more sophisticated interface.
62
63 A Cmd instance or subclass instance is a line-oriented interpreter
64 framework. There is no good reason to instantiate Cmd itself; rather,
65 it's useful as a superclass of an interpreter class you define yourself
66 in order to inherit Cmd's methods and encapsulate action methods.
67
68 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +000069 prompt = PROMPT
70 identchars = IDENTCHARS
71 ruler = '='
72 lastcmd = ''
Guido van Rossum4acc25b2000-02-02 15:10:15 +000073 intro = None
74 doc_leader = ""
75 doc_header = "Documented commands (type help <topic>):"
76 misc_header = "Miscellaneous help topics:"
77 undoc_header = "Undocumented commands:"
78 nohelp = "*** No help on %s"
Guido van Rossumbfb91842001-03-22 21:59:20 +000079 use_rawinput = 1
Guido van Rossum9b3bc711993-06-20 21:02:22 +000080
Anthony Baxter983b0082003-02-06 01:45:11 +000081 def __init__(self, completekey='tab', stdin=None, stdout=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000082 """Instantiate a line-oriented interpreter framework.
83
Tim Petersf2715e02003-02-19 02:35:07 +000084 The optional argument 'completekey' is the readline name of a
85 completion key; it defaults to the Tab key. If completekey is
86 not None and the readline module is available, command completion
Anthony Baxter983b0082003-02-06 01:45:11 +000087 is done automatically. The optional arguments stdin and stdout
88 specify alternate input and output file objects; if not specified,
89 sys.stdin and sys.stdout are used.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000090
91 """
Anthony Baxter983b0082003-02-06 01:45:11 +000092 import sys
93 if stdin is not None:
94 self.stdin = stdin
95 else:
96 self.stdin = sys.stdin
97 if stdout is not None:
98 self.stdout = stdout
99 else:
100 self.stdout = sys.stdout
Guido van Rossum87fec222003-01-13 21:18:54 +0000101 self.cmdqueue = []
Michael W. Hudson35a92ce2003-02-03 11:04:27 +0000102 self.completekey = completekey
Guido van Rossum030eb111998-07-01 22:53:04 +0000103
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000104 def cmdloop(self, intro=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000105 """Repeatedly issue a prompt, accept input, parse an initial prefix
106 off the received input, and dispatch to action methods, passing them
107 the remainder of the line as argument.
108
109 """
110
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000111 self.preloop()
Michael W. Hudsond7cc1bd2004-07-01 14:52:10 +0000112 if self.use_rawinput and self.completekey:
113 try:
114 import readline
115 self.old_completer = readline.get_completer()
116 readline.set_completer(self.complete)
117 readline.parse_and_bind(self.completekey+": complete")
118 except ImportError:
119 pass
120 try:
121 if intro is not None:
122 self.intro = intro
123 if self.intro:
124 self.stdout.write(str(self.intro)+"\n")
125 stop = None
126 while not stop:
127 if self.cmdqueue:
128 line = self.cmdqueue.pop(0)
Guido van Rossumbfb91842001-03-22 21:59:20 +0000129 else:
Michael W. Hudsond7cc1bd2004-07-01 14:52:10 +0000130 if self.use_rawinput:
131 try:
132 line = raw_input(self.prompt)
133 except EOFError:
134 line = 'EOF'
Guido van Rossumbfb91842001-03-22 21:59:20 +0000135 else:
Michael W. Hudsond7cc1bd2004-07-01 14:52:10 +0000136 self.stdout.write(self.prompt)
137 self.stdout.flush()
138 line = self.stdin.readline()
139 if not len(line):
140 line = 'EOF'
141 else:
142 line = line[:-1] # chop \n
143 line = self.precmd(line)
144 stop = self.onecmd(line)
145 stop = self.postcmd(stop, line)
146 self.postloop()
147 finally:
148 if self.use_rawinput and self.completekey:
149 try:
150 import readline
151 readline.set_completer(self.old_completer)
152 except ImportError:
153 pass
Tim Peters4e0e1b62004-07-07 20:54:48 +0000154
Guido van Rossum80884071998-06-29 17:58:55 +0000155
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000156 def precmd(self, line):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000157 """Hook method executed just before the command line is
158 interpreted, but after the input prompt is generated and issued.
159
160 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000161 return line
Guido van Rossum80884071998-06-29 17:58:55 +0000162
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000163 def postcmd(self, stop, line):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000164 """Hook method executed just after a command dispatch is finished."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000165 return stop
Guido van Rossum80884071998-06-29 17:58:55 +0000166
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000167 def preloop(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000168 """Hook method executed once when the cmdloop() method is called."""
Michael W. Hudsond7cc1bd2004-07-01 14:52:10 +0000169 pass
Guido van Rossum80884071998-06-29 17:58:55 +0000170
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000171 def postloop(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000172 """Hook method executed once when the cmdloop() method is about to
173 return.
174
175 """
Michael W. Hudsond7cc1bd2004-07-01 14:52:10 +0000176 pass
Tim Peters4e0e1b62004-07-07 20:54:48 +0000177
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000178 def parseline(self, line):
Andrew M. Kuchling7cebbf32003-10-22 14:38:54 +0000179 """Parse the line into a command name and a string containing
180 the arguments. Returns a tuple containing (command, args, line).
181 'command' and 'args' may be None if the line couldn't be parsed.
182 """
Eric S. Raymond20e44232001-02-09 04:52:11 +0000183 line = line.strip()
Eric S. Raymond5f1b2702000-07-11 13:03:55 +0000184 if not line:
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000185 return None, None, line
Eric S. Raymond5f1b2702000-07-11 13:03:55 +0000186 elif line[0] == '?':
187 line = 'help ' + line[1:]
188 elif line[0] == '!':
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000189 if hasattr(self, 'do_shell'):
Eric S. Raymond5f1b2702000-07-11 13:03:55 +0000190 line = 'shell ' + line[1:]
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000191 else:
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000192 return None, None, line
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000193 i, n = 0, len(line)
194 while i < n and line[i] in self.identchars: i = i+1
Eric S. Raymond20e44232001-02-09 04:52:11 +0000195 cmd, arg = line[:i], line[i:].strip()
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000196 return cmd, arg, line
Tim Petersab9ba272001-08-09 21:40:30 +0000197
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000198 def onecmd(self, line):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000199 """Interpret the argument as though it had been typed in response
200 to the prompt.
201
202 This may be overridden, but should not normally need to be;
203 see the precmd() and postcmd() methods for useful execution hooks.
204 The return value is a flag indicating whether interpretation of
205 commands by the interpreter should stop.
206
207 """
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000208 cmd, arg, line = self.parseline(line)
209 if not line:
210 return self.emptyline()
211 if cmd is None:
212 return self.default(line)
213 self.lastcmd = line
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000214 if cmd == '':
215 return self.default(line)
216 else:
217 try:
218 func = getattr(self, 'do_' + cmd)
219 except AttributeError:
220 return self.default(line)
221 return func(arg)
Guido van Rossumb53e6781992-01-24 01:12:17 +0000222
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000223 def emptyline(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000224 """Called when an empty line is entered in response to the prompt.
225
226 If this method is not overridden, it repeats the last nonempty
227 command entered.
228
229 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000230 if self.lastcmd:
231 return self.onecmd(self.lastcmd)
Guido van Rossum80884071998-06-29 17:58:55 +0000232
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000233 def default(self, line):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000234 """Called on an input line when the command prefix is not recognized.
235
236 If this method is not overridden, it prints an error message and
237 returns.
238
239 """
Anthony Baxter983b0082003-02-06 01:45:11 +0000240 self.stdout.write('*** Unknown syntax: %s\n'%line)
Guido van Rossumb53e6781992-01-24 01:12:17 +0000241
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000242 def completedefault(self, *ignored):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000243 """Method called to complete an input line when no command-specific
244 complete_*() method is available.
245
246 By default, it returns an empty list.
247
248 """
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000249 return []
250
251 def completenames(self, text, *ignored):
252 dotext = 'do_'+text
253 return [a[3:] for a in self.get_names() if a.startswith(dotext)]
254
255 def complete(self, text, state):
256 """Return the next possible completion for 'text'.
257
258 If a command has not been entered, then complete against command list.
259 Otherwise try to call complete_<command> to get list of completions.
260 """
261 if state == 0:
262 import readline
263 origline = readline.get_line_buffer()
264 line = origline.lstrip()
265 stripped = len(origline) - len(line)
266 begidx = readline.get_begidx() - stripped
267 endidx = readline.get_endidx() - stripped
268 if begidx>0:
269 cmd, args, foo = self.parseline(line)
270 if cmd == '':
271 compfunc = self.completedefault
272 else:
273 try:
274 compfunc = getattr(self, 'complete_' + cmd)
275 except AttributeError:
276 compfunc = self.completedefault
277 else:
278 compfunc = self.completenames
279 self.completion_matches = compfunc(text, line, begidx, endidx)
280 try:
281 return self.completion_matches[state]
282 except IndexError:
283 return None
Tim Petersab9ba272001-08-09 21:40:30 +0000284
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000285 def get_names(self):
286 # Inheritance says we have to look in class and
287 # base classes; order is not important.
288 names = []
289 classes = [self.__class__]
290 while classes:
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000291 aclass = classes.pop(0)
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000292 if aclass.__bases__:
293 classes = classes + list(aclass.__bases__)
294 names = names + dir(aclass)
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000295 return names
296
297 def complete_help(self, *args):
298 return self.completenames(*args)
299
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000300 def do_help(self, arg):
301 if arg:
302 # XXX check arg syntax
303 try:
304 func = getattr(self, 'help_' + arg)
Skip Montanaro1ce00732002-03-24 16:34:21 +0000305 except AttributeError:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000306 try:
307 doc=getattr(self, 'do_' + arg).__doc__
308 if doc:
Anthony Baxter983b0082003-02-06 01:45:11 +0000309 self.stdout.write("%s\n"%str(doc))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000310 return
Skip Montanaro1ce00732002-03-24 16:34:21 +0000311 except AttributeError:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000312 pass
Anthony Baxter983b0082003-02-06 01:45:11 +0000313 self.stdout.write("%s\n"%str(self.nohelp % (arg,)))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000314 return
315 func()
316 else:
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000317 names = self.get_names()
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000318 cmds_doc = []
319 cmds_undoc = []
320 help = {}
321 for name in names:
322 if name[:5] == 'help_':
323 help[name[5:]]=1
324 names.sort()
325 # There can be duplicates if routines overridden
326 prevname = ''
327 for name in names:
328 if name[:3] == 'do_':
329 if name == prevname:
330 continue
331 prevname = name
332 cmd=name[3:]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000333 if cmd in help:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000334 cmds_doc.append(cmd)
335 del help[cmd]
336 elif getattr(self, name).__doc__:
337 cmds_doc.append(cmd)
338 else:
339 cmds_undoc.append(cmd)
Anthony Baxter983b0082003-02-06 01:45:11 +0000340 self.stdout.write("%s\n"%str(self.doc_leader))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000341 self.print_topics(self.doc_header, cmds_doc, 15,80)
342 self.print_topics(self.misc_header, help.keys(),15,80)
343 self.print_topics(self.undoc_header, cmds_undoc, 15,80)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000344
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000345 def print_topics(self, header, cmds, cmdlen, maxcol):
346 if cmds:
Anthony Baxter983b0082003-02-06 01:45:11 +0000347 self.stdout.write("%s\n"%str(header))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000348 if self.ruler:
Anthony Baxter983b0082003-02-06 01:45:11 +0000349 self.stdout.write("%s\n"%str(self.ruler * len(header)))
Guido van Rossumc706c282002-12-02 13:08:53 +0000350 self.columnize(cmds, maxcol-1)
Anthony Baxter983b0082003-02-06 01:45:11 +0000351 self.stdout.write("\n")
Guido van Rossumc706c282002-12-02 13:08:53 +0000352
353 def columnize(self, list, displaywidth=80):
354 """Display a list of strings as a compact set of columns.
355
356 Each column is only as wide as necessary.
357 Columns are separated by two spaces (one was not legible enough).
358 """
359 if not list:
Anthony Baxter983b0082003-02-06 01:45:11 +0000360 self.stdout.write("<empty>\n")
Guido van Rossumc706c282002-12-02 13:08:53 +0000361 return
362 nonstrings = [i for i in range(len(list))
363 if not isinstance(list[i], str)]
364 if nonstrings:
365 raise TypeError, ("list[i] not a string for i in %s" %
366 ", ".join(map(str, nonstrings)))
367 size = len(list)
368 if size == 1:
Anthony Baxter983b0082003-02-06 01:45:11 +0000369 self.stdout.write('%s\n'%str(list[0]))
Guido van Rossumc706c282002-12-02 13:08:53 +0000370 return
371 # Try every row count from 1 upwards
372 for nrows in range(1, len(list)):
373 ncols = (size+nrows-1) // nrows
374 colwidths = []
375 totwidth = -2
376 for col in range(ncols):
377 colwidth = 0
378 for row in range(nrows):
379 i = row + nrows*col
380 if i >= size:
381 break
382 x = list[i]
383 colwidth = max(colwidth, len(x))
384 colwidths.append(colwidth)
385 totwidth += colwidth + 2
386 if totwidth > displaywidth:
387 break
388 if totwidth <= displaywidth:
389 break
390 else:
391 nrows = len(list)
392 ncols = 1
393 colwidths = [0]
394 for row in range(nrows):
395 texts = []
396 for col in range(ncols):
397 i = row + nrows*col
398 if i >= size:
399 x = ""
400 else:
401 x = list[i]
402 texts.append(x)
403 while texts and not texts[-1]:
404 del texts[-1]
405 for col in range(len(texts)):
406 texts[col] = texts[col].ljust(colwidths[col])
Anthony Baxter983b0082003-02-06 01:45:11 +0000407 self.stdout.write("%s\n"%str(" ".join(texts)))