blob: 8fa7d019b5505ed9bd9f6b810916f3bd6ddb7b64 [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
52class Cmd:
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000053 """A simple framework for writing line-oriented command interpreters.
54
55 These are often useful for test harnesses, administrative tools, and
56 prototypes that will later be wrapped in a more sophisticated interface.
57
58 A Cmd instance or subclass instance is a line-oriented interpreter
59 framework. There is no good reason to instantiate Cmd itself; rather,
60 it's useful as a superclass of an interpreter class you define yourself
61 in order to inherit Cmd's methods and encapsulate action methods.
62
63 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +000064 prompt = PROMPT
65 identchars = IDENTCHARS
66 ruler = '='
67 lastcmd = ''
Guido van Rossum4acc25b2000-02-02 15:10:15 +000068 intro = None
69 doc_leader = ""
70 doc_header = "Documented commands (type help <topic>):"
71 misc_header = "Miscellaneous help topics:"
72 undoc_header = "Undocumented commands:"
73 nohelp = "*** No help on %s"
Guido van Rossumbfb91842001-03-22 21:59:20 +000074 use_rawinput = 1
Guido van Rossum9b3bc711993-06-20 21:02:22 +000075
Anthony Baxter983b0082003-02-06 01:45:11 +000076 def __init__(self, completekey='tab', stdin=None, stdout=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000077 """Instantiate a line-oriented interpreter framework.
78
Tim Petersf2715e02003-02-19 02:35:07 +000079 The optional argument 'completekey' is the readline name of a
80 completion key; it defaults to the Tab key. If completekey is
81 not None and the readline module is available, command completion
Anthony Baxter983b0082003-02-06 01:45:11 +000082 is done automatically. The optional arguments stdin and stdout
83 specify alternate input and output file objects; if not specified,
84 sys.stdin and sys.stdout are used.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000085
86 """
Anthony Baxter983b0082003-02-06 01:45:11 +000087 if stdin is not None:
88 self.stdin = stdin
89 else:
90 self.stdin = sys.stdin
91 if stdout is not None:
92 self.stdout = stdout
93 else:
94 self.stdout = sys.stdout
Guido van Rossum87fec222003-01-13 21:18:54 +000095 self.cmdqueue = []
Michael W. Hudson35a92ce2003-02-03 11:04:27 +000096 self.completekey = completekey
Guido van Rossum030eb111998-07-01 22:53:04 +000097
Guido van Rossum4acc25b2000-02-02 15:10:15 +000098 def cmdloop(self, intro=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000099 """Repeatedly issue a prompt, accept input, parse an initial prefix
100 off the received input, and dispatch to action methods, passing them
101 the remainder of the line as argument.
102
103 """
104
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000105 self.preloop()
Michael W. Hudsond7cc1bd2004-07-01 14:52:10 +0000106 if self.use_rawinput and self.completekey:
107 try:
108 import readline
109 self.old_completer = readline.get_completer()
110 readline.set_completer(self.complete)
111 readline.parse_and_bind(self.completekey+": complete")
112 except ImportError:
113 pass
114 try:
115 if intro is not None:
116 self.intro = intro
117 if self.intro:
118 self.stdout.write(str(self.intro)+"\n")
119 stop = None
120 while not stop:
121 if self.cmdqueue:
122 line = self.cmdqueue.pop(0)
Guido van Rossumbfb91842001-03-22 21:59:20 +0000123 else:
Michael W. Hudsond7cc1bd2004-07-01 14:52:10 +0000124 if self.use_rawinput:
125 try:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000126 line = input(self.prompt)
Michael W. Hudsond7cc1bd2004-07-01 14:52:10 +0000127 except EOFError:
128 line = 'EOF'
Guido van Rossumbfb91842001-03-22 21:59:20 +0000129 else:
Michael W. Hudsond7cc1bd2004-07-01 14:52:10 +0000130 self.stdout.write(self.prompt)
131 self.stdout.flush()
132 line = self.stdin.readline()
133 if not len(line):
134 line = 'EOF'
135 else:
R. David Murray7905d612010-08-01 03:31:09 +0000136 line = line.rstrip('\r\n')
Michael W. Hudsond7cc1bd2004-07-01 14:52:10 +0000137 line = self.precmd(line)
138 stop = self.onecmd(line)
139 stop = self.postcmd(stop, line)
140 self.postloop()
141 finally:
142 if self.use_rawinput and self.completekey:
143 try:
144 import readline
145 readline.set_completer(self.old_completer)
146 except ImportError:
147 pass
Tim Peters4e0e1b62004-07-07 20:54:48 +0000148
Guido van Rossum80884071998-06-29 17:58:55 +0000149
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000150 def precmd(self, line):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000151 """Hook method executed just before the command line is
152 interpreted, but after the input prompt is generated and issued.
153
154 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000155 return line
Guido van Rossum80884071998-06-29 17:58:55 +0000156
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000157 def postcmd(self, stop, line):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000158 """Hook method executed just after a command dispatch is finished."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000159 return stop
Guido van Rossum80884071998-06-29 17:58:55 +0000160
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000161 def preloop(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000162 """Hook method executed once when the cmdloop() method is called."""
Michael W. Hudsond7cc1bd2004-07-01 14:52:10 +0000163 pass
Guido van Rossum80884071998-06-29 17:58:55 +0000164
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000165 def postloop(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000166 """Hook method executed once when the cmdloop() method is about to
167 return.
168
169 """
Michael W. Hudsond7cc1bd2004-07-01 14:52:10 +0000170 pass
Tim Peters4e0e1b62004-07-07 20:54:48 +0000171
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000172 def parseline(self, line):
Andrew M. Kuchling7cebbf32003-10-22 14:38:54 +0000173 """Parse the line into a command name and a string containing
174 the arguments. Returns a tuple containing (command, args, line).
175 'command' and 'args' may be None if the line couldn't be parsed.
176 """
Eric S. Raymond20e44232001-02-09 04:52:11 +0000177 line = line.strip()
Eric S. Raymond5f1b2702000-07-11 13:03:55 +0000178 if not line:
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000179 return None, None, line
Eric S. Raymond5f1b2702000-07-11 13:03:55 +0000180 elif line[0] == '?':
181 line = 'help ' + line[1:]
182 elif line[0] == '!':
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000183 if hasattr(self, 'do_shell'):
Eric S. Raymond5f1b2702000-07-11 13:03:55 +0000184 line = 'shell ' + line[1:]
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000185 else:
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000186 return None, None, line
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000187 i, n = 0, len(line)
188 while i < n and line[i] in self.identchars: i = i+1
Eric S. Raymond20e44232001-02-09 04:52:11 +0000189 cmd, arg = line[:i], line[i:].strip()
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000190 return cmd, arg, line
Tim Petersab9ba272001-08-09 21:40:30 +0000191
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000192 def onecmd(self, line):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000193 """Interpret the argument as though it had been typed in response
194 to the prompt.
195
196 This may be overridden, but should not normally need to be;
197 see the precmd() and postcmd() methods for useful execution hooks.
198 The return value is a flag indicating whether interpretation of
199 commands by the interpreter should stop.
200
201 """
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000202 cmd, arg, line = self.parseline(line)
203 if not line:
204 return self.emptyline()
205 if cmd is None:
206 return self.default(line)
207 self.lastcmd = line
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000208 if cmd == '':
209 return self.default(line)
210 else:
211 try:
212 func = getattr(self, 'do_' + cmd)
213 except AttributeError:
214 return self.default(line)
215 return func(arg)
Guido van Rossumb53e6781992-01-24 01:12:17 +0000216
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000217 def emptyline(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000218 """Called when an empty line is entered in response to the prompt.
219
220 If this method is not overridden, it repeats the last nonempty
221 command entered.
222
223 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000224 if self.lastcmd:
225 return self.onecmd(self.lastcmd)
Guido van Rossum80884071998-06-29 17:58:55 +0000226
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000227 def default(self, line):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000228 """Called on an input line when the command prefix is not recognized.
229
230 If this method is not overridden, it prints an error message and
231 returns.
232
233 """
Anthony Baxter983b0082003-02-06 01:45:11 +0000234 self.stdout.write('*** Unknown syntax: %s\n'%line)
Guido van Rossumb53e6781992-01-24 01:12:17 +0000235
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000236 def completedefault(self, *ignored):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000237 """Method called to complete an input line when no command-specific
238 complete_*() method is available.
239
240 By default, it returns an empty list.
241
242 """
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000243 return []
244
245 def completenames(self, text, *ignored):
246 dotext = 'do_'+text
247 return [a[3:] for a in self.get_names() if a.startswith(dotext)]
248
249 def complete(self, text, state):
250 """Return the next possible completion for 'text'.
251
252 If a command has not been entered, then complete against command list.
253 Otherwise try to call complete_<command> to get list of completions.
254 """
255 if state == 0:
256 import readline
257 origline = readline.get_line_buffer()
258 line = origline.lstrip()
259 stripped = len(origline) - len(line)
260 begidx = readline.get_begidx() - stripped
261 endidx = readline.get_endidx() - stripped
262 if begidx>0:
263 cmd, args, foo = self.parseline(line)
264 if cmd == '':
265 compfunc = self.completedefault
266 else:
267 try:
268 compfunc = getattr(self, 'complete_' + cmd)
269 except AttributeError:
270 compfunc = self.completedefault
271 else:
272 compfunc = self.completenames
273 self.completion_matches = compfunc(text, line, begidx, endidx)
274 try:
275 return self.completion_matches[state]
276 except IndexError:
277 return None
Tim Petersab9ba272001-08-09 21:40:30 +0000278
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000279 def get_names(self):
Benjamin Petersona28e7022010-01-09 18:53:06 +0000280 # This method used to pull in base class attributes
281 # at a time dir() didn't do it yet.
282 return dir(self.__class__)
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000283
284 def complete_help(self, *args):
Benjamin Petersona28e7022010-01-09 18:53:06 +0000285 commands = set(self.completenames(*args))
286 topics = set(a[5:] for a in self.get_names()
287 if a.startswith('help_' + args[0]))
288 return list(commands | topics)
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000289
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000290 def do_help(self, arg):
Raymond Hettinger44d7b6a2010-09-09 03:53:22 +0000291 'List available commands with "help" or detailed help with "help cmd".'
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000292 if arg:
293 # XXX check arg syntax
294 try:
295 func = getattr(self, 'help_' + arg)
Skip Montanaro1ce00732002-03-24 16:34:21 +0000296 except AttributeError:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000297 try:
298 doc=getattr(self, 'do_' + arg).__doc__
299 if doc:
Anthony Baxter983b0082003-02-06 01:45:11 +0000300 self.stdout.write("%s\n"%str(doc))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000301 return
Skip Montanaro1ce00732002-03-24 16:34:21 +0000302 except AttributeError:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000303 pass
Anthony Baxter983b0082003-02-06 01:45:11 +0000304 self.stdout.write("%s\n"%str(self.nohelp % (arg,)))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000305 return
306 func()
307 else:
Martin v. Löwis66b6e192001-07-28 14:44:03 +0000308 names = self.get_names()
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000309 cmds_doc = []
310 cmds_undoc = []
311 help = {}
312 for name in names:
313 if name[:5] == 'help_':
314 help[name[5:]]=1
315 names.sort()
316 # There can be duplicates if routines overridden
317 prevname = ''
318 for name in names:
319 if name[:3] == 'do_':
320 if name == prevname:
321 continue
322 prevname = name
323 cmd=name[3:]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000324 if cmd in help:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000325 cmds_doc.append(cmd)
326 del help[cmd]
327 elif getattr(self, name).__doc__:
328 cmds_doc.append(cmd)
329 else:
330 cmds_undoc.append(cmd)
Anthony Baxter983b0082003-02-06 01:45:11 +0000331 self.stdout.write("%s\n"%str(self.doc_leader))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000332 self.print_topics(self.doc_header, cmds_doc, 15,80)
Alexandre Vassalotti7b955bd2007-06-07 22:37:45 +0000333 self.print_topics(self.misc_header, list(help.keys()),15,80)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000334 self.print_topics(self.undoc_header, cmds_undoc, 15,80)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000335
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000336 def print_topics(self, header, cmds, cmdlen, maxcol):
337 if cmds:
Anthony Baxter983b0082003-02-06 01:45:11 +0000338 self.stdout.write("%s\n"%str(header))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000339 if self.ruler:
Anthony Baxter983b0082003-02-06 01:45:11 +0000340 self.stdout.write("%s\n"%str(self.ruler * len(header)))
Guido van Rossumc706c282002-12-02 13:08:53 +0000341 self.columnize(cmds, maxcol-1)
Anthony Baxter983b0082003-02-06 01:45:11 +0000342 self.stdout.write("\n")
Guido van Rossumc706c282002-12-02 13:08:53 +0000343
344 def columnize(self, list, displaywidth=80):
345 """Display a list of strings as a compact set of columns.
346
347 Each column is only as wide as necessary.
348 Columns are separated by two spaces (one was not legible enough).
349 """
350 if not list:
Anthony Baxter983b0082003-02-06 01:45:11 +0000351 self.stdout.write("<empty>\n")
Guido van Rossumc706c282002-12-02 13:08:53 +0000352 return
Alexandre Vassalotti7b955bd2007-06-07 22:37:45 +0000353
Guido van Rossumc706c282002-12-02 13:08:53 +0000354 nonstrings = [i for i in range(len(list))
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000355 if not isinstance(list[i], str)]
Guido van Rossumc706c282002-12-02 13:08:53 +0000356 if nonstrings:
Collin Winterce36ad82007-08-30 01:19:48 +0000357 raise TypeError("list[i] not a string for i in %s"
358 % ", ".join(map(str, nonstrings)))
Guido van Rossumc706c282002-12-02 13:08:53 +0000359 size = len(list)
360 if size == 1:
Anthony Baxter983b0082003-02-06 01:45:11 +0000361 self.stdout.write('%s\n'%str(list[0]))
Guido van Rossumc706c282002-12-02 13:08:53 +0000362 return
363 # Try every row count from 1 upwards
364 for nrows in range(1, len(list)):
365 ncols = (size+nrows-1) // nrows
366 colwidths = []
367 totwidth = -2
368 for col in range(ncols):
369 colwidth = 0
370 for row in range(nrows):
371 i = row + nrows*col
372 if i >= size:
373 break
374 x = list[i]
375 colwidth = max(colwidth, len(x))
376 colwidths.append(colwidth)
377 totwidth += colwidth + 2
378 if totwidth > displaywidth:
379 break
380 if totwidth <= displaywidth:
381 break
382 else:
383 nrows = len(list)
384 ncols = 1
385 colwidths = [0]
386 for row in range(nrows):
387 texts = []
388 for col in range(ncols):
389 i = row + nrows*col
390 if i >= size:
391 x = ""
392 else:
393 x = list[i]
394 texts.append(x)
395 while texts and not texts[-1]:
396 del texts[-1]
397 for col in range(len(texts)):
398 texts[col] = texts[col].ljust(colwidths[col])
Anthony Baxter983b0082003-02-06 01:45:11 +0000399 self.stdout.write("%s\n"%str(" ".join(texts)))