1 | n/a | """A generic class to build line-oriented command interpreters. |
---|
2 | n/a | |
---|
3 | n/a | Interpreters constructed with this class obey the following conventions: |
---|
4 | n/a | |
---|
5 | n/a | 1. End of file on input is processed as the command 'EOF'. |
---|
6 | n/a | 2. A command is parsed out of each line by collecting the prefix composed |
---|
7 | n/a | of characters in the identchars member. |
---|
8 | n/a | 3. A command `foo' is dispatched to a method 'do_foo()'; the do_ method |
---|
9 | n/a | is passed a single argument consisting of the remainder of the line. |
---|
10 | n/a | 4. Typing an empty line repeats the last command. (Actually, it calls the |
---|
11 | n/a | method `emptyline', which may be overridden in a subclass.) |
---|
12 | n/a | 5. There is a predefined `help' method. Given an argument `topic', it |
---|
13 | n/a | calls the command `help_topic'. With no arguments, it lists all topics |
---|
14 | n/a | with defined help_ functions, broken into up to three topics; documented |
---|
15 | n/a | commands, miscellaneous help topics, and undocumented commands. |
---|
16 | n/a | 6. The command '?' is a synonym for `help'. The command '!' is a synonym |
---|
17 | n/a | for `shell', if a do_shell method exists. |
---|
18 | n/a | 7. If completion is enabled, completing commands will be done automatically, |
---|
19 | n/a | and completing of commands args is done by calling complete_foo() with |
---|
20 | n/a | arguments text, line, begidx, endidx. text is string we are matching |
---|
21 | n/a | against, all returned matches must begin with it. line is the current |
---|
22 | n/a | input line (lstripped), begidx and endidx are the beginning and end |
---|
23 | n/a | indexes of the text being matched, which could be used to provide |
---|
24 | n/a | different completion depending upon which position the argument is in. |
---|
25 | n/a | |
---|
26 | n/a | The `default' method may be overridden to intercept commands for which there |
---|
27 | n/a | is no do_ method. |
---|
28 | n/a | |
---|
29 | n/a | The `completedefault' method may be overridden to intercept completions for |
---|
30 | n/a | commands that have no complete_ method. |
---|
31 | n/a | |
---|
32 | n/a | The data member `self.ruler' sets the character used to draw separator lines |
---|
33 | n/a | in the help messages. If empty, no ruler line is drawn. It defaults to "=". |
---|
34 | n/a | |
---|
35 | n/a | If the value of `self.intro' is nonempty when the cmdloop method is called, |
---|
36 | n/a | it is printed out on interpreter startup. This value may be overridden |
---|
37 | n/a | via an optional argument to the cmdloop() method. |
---|
38 | n/a | |
---|
39 | n/a | The data members `self.doc_header', `self.misc_header', and |
---|
40 | n/a | `self.undoc_header' set the headers used for the help function's |
---|
41 | n/a | listings of documented functions, miscellaneous topics, and undocumented |
---|
42 | n/a | functions respectively. |
---|
43 | n/a | """ |
---|
44 | n/a | |
---|
45 | n/a | import string, sys |
---|
46 | n/a | |
---|
47 | n/a | __all__ = ["Cmd"] |
---|
48 | n/a | |
---|
49 | n/a | PROMPT = '(Cmd) ' |
---|
50 | n/a | IDENTCHARS = string.ascii_letters + string.digits + '_' |
---|
51 | n/a | |
---|
52 | n/a | class Cmd: |
---|
53 | n/a | """A simple framework for writing line-oriented command interpreters. |
---|
54 | n/a | |
---|
55 | n/a | These are often useful for test harnesses, administrative tools, and |
---|
56 | n/a | prototypes that will later be wrapped in a more sophisticated interface. |
---|
57 | n/a | |
---|
58 | n/a | A Cmd instance or subclass instance is a line-oriented interpreter |
---|
59 | n/a | framework. There is no good reason to instantiate Cmd itself; rather, |
---|
60 | n/a | it's useful as a superclass of an interpreter class you define yourself |
---|
61 | n/a | in order to inherit Cmd's methods and encapsulate action methods. |
---|
62 | n/a | |
---|
63 | n/a | """ |
---|
64 | n/a | prompt = PROMPT |
---|
65 | n/a | identchars = IDENTCHARS |
---|
66 | n/a | ruler = '=' |
---|
67 | n/a | lastcmd = '' |
---|
68 | n/a | intro = None |
---|
69 | n/a | doc_leader = "" |
---|
70 | n/a | doc_header = "Documented commands (type help <topic>):" |
---|
71 | n/a | misc_header = "Miscellaneous help topics:" |
---|
72 | n/a | undoc_header = "Undocumented commands:" |
---|
73 | n/a | nohelp = "*** No help on %s" |
---|
74 | n/a | use_rawinput = 1 |
---|
75 | n/a | |
---|
76 | n/a | def __init__(self, completekey='tab', stdin=None, stdout=None): |
---|
77 | n/a | """Instantiate a line-oriented interpreter framework. |
---|
78 | n/a | |
---|
79 | n/a | The optional argument 'completekey' is the readline name of a |
---|
80 | n/a | completion key; it defaults to the Tab key. If completekey is |
---|
81 | n/a | not None and the readline module is available, command completion |
---|
82 | n/a | is done automatically. The optional arguments stdin and stdout |
---|
83 | n/a | specify alternate input and output file objects; if not specified, |
---|
84 | n/a | sys.stdin and sys.stdout are used. |
---|
85 | n/a | |
---|
86 | n/a | """ |
---|
87 | n/a | if stdin is not None: |
---|
88 | n/a | self.stdin = stdin |
---|
89 | n/a | else: |
---|
90 | n/a | self.stdin = sys.stdin |
---|
91 | n/a | if stdout is not None: |
---|
92 | n/a | self.stdout = stdout |
---|
93 | n/a | else: |
---|
94 | n/a | self.stdout = sys.stdout |
---|
95 | n/a | self.cmdqueue = [] |
---|
96 | n/a | self.completekey = completekey |
---|
97 | n/a | |
---|
98 | n/a | def cmdloop(self, intro=None): |
---|
99 | n/a | """Repeatedly issue a prompt, accept input, parse an initial prefix |
---|
100 | n/a | off the received input, and dispatch to action methods, passing them |
---|
101 | n/a | the remainder of the line as argument. |
---|
102 | n/a | |
---|
103 | n/a | """ |
---|
104 | n/a | |
---|
105 | n/a | self.preloop() |
---|
106 | n/a | if self.use_rawinput and self.completekey: |
---|
107 | n/a | try: |
---|
108 | n/a | import readline |
---|
109 | n/a | self.old_completer = readline.get_completer() |
---|
110 | n/a | readline.set_completer(self.complete) |
---|
111 | n/a | readline.parse_and_bind(self.completekey+": complete") |
---|
112 | n/a | except ImportError: |
---|
113 | n/a | pass |
---|
114 | n/a | try: |
---|
115 | n/a | if intro is not None: |
---|
116 | n/a | self.intro = intro |
---|
117 | n/a | if self.intro: |
---|
118 | n/a | self.stdout.write(str(self.intro)+"\n") |
---|
119 | n/a | stop = None |
---|
120 | n/a | while not stop: |
---|
121 | n/a | if self.cmdqueue: |
---|
122 | n/a | line = self.cmdqueue.pop(0) |
---|
123 | n/a | else: |
---|
124 | n/a | if self.use_rawinput: |
---|
125 | n/a | try: |
---|
126 | n/a | line = input(self.prompt) |
---|
127 | n/a | except EOFError: |
---|
128 | n/a | line = 'EOF' |
---|
129 | n/a | else: |
---|
130 | n/a | self.stdout.write(self.prompt) |
---|
131 | n/a | self.stdout.flush() |
---|
132 | n/a | line = self.stdin.readline() |
---|
133 | n/a | if not len(line): |
---|
134 | n/a | line = 'EOF' |
---|
135 | n/a | else: |
---|
136 | n/a | line = line.rstrip('\r\n') |
---|
137 | n/a | line = self.precmd(line) |
---|
138 | n/a | stop = self.onecmd(line) |
---|
139 | n/a | stop = self.postcmd(stop, line) |
---|
140 | n/a | self.postloop() |
---|
141 | n/a | finally: |
---|
142 | n/a | if self.use_rawinput and self.completekey: |
---|
143 | n/a | try: |
---|
144 | n/a | import readline |
---|
145 | n/a | readline.set_completer(self.old_completer) |
---|
146 | n/a | except ImportError: |
---|
147 | n/a | pass |
---|
148 | n/a | |
---|
149 | n/a | |
---|
150 | n/a | def precmd(self, line): |
---|
151 | n/a | """Hook method executed just before the command line is |
---|
152 | n/a | interpreted, but after the input prompt is generated and issued. |
---|
153 | n/a | |
---|
154 | n/a | """ |
---|
155 | n/a | return line |
---|
156 | n/a | |
---|
157 | n/a | def postcmd(self, stop, line): |
---|
158 | n/a | """Hook method executed just after a command dispatch is finished.""" |
---|
159 | n/a | return stop |
---|
160 | n/a | |
---|
161 | n/a | def preloop(self): |
---|
162 | n/a | """Hook method executed once when the cmdloop() method is called.""" |
---|
163 | n/a | pass |
---|
164 | n/a | |
---|
165 | n/a | def postloop(self): |
---|
166 | n/a | """Hook method executed once when the cmdloop() method is about to |
---|
167 | n/a | return. |
---|
168 | n/a | |
---|
169 | n/a | """ |
---|
170 | n/a | pass |
---|
171 | n/a | |
---|
172 | n/a | def parseline(self, line): |
---|
173 | n/a | """Parse the line into a command name and a string containing |
---|
174 | n/a | the arguments. Returns a tuple containing (command, args, line). |
---|
175 | n/a | 'command' and 'args' may be None if the line couldn't be parsed. |
---|
176 | n/a | """ |
---|
177 | n/a | line = line.strip() |
---|
178 | n/a | if not line: |
---|
179 | n/a | return None, None, line |
---|
180 | n/a | elif line[0] == '?': |
---|
181 | n/a | line = 'help ' + line[1:] |
---|
182 | n/a | elif line[0] == '!': |
---|
183 | n/a | if hasattr(self, 'do_shell'): |
---|
184 | n/a | line = 'shell ' + line[1:] |
---|
185 | n/a | else: |
---|
186 | n/a | return None, None, line |
---|
187 | n/a | i, n = 0, len(line) |
---|
188 | n/a | while i < n and line[i] in self.identchars: i = i+1 |
---|
189 | n/a | cmd, arg = line[:i], line[i:].strip() |
---|
190 | n/a | return cmd, arg, line |
---|
191 | n/a | |
---|
192 | n/a | def onecmd(self, line): |
---|
193 | n/a | """Interpret the argument as though it had been typed in response |
---|
194 | n/a | to the prompt. |
---|
195 | n/a | |
---|
196 | n/a | This may be overridden, but should not normally need to be; |
---|
197 | n/a | see the precmd() and postcmd() methods for useful execution hooks. |
---|
198 | n/a | The return value is a flag indicating whether interpretation of |
---|
199 | n/a | commands by the interpreter should stop. |
---|
200 | n/a | |
---|
201 | n/a | """ |
---|
202 | n/a | cmd, arg, line = self.parseline(line) |
---|
203 | n/a | if not line: |
---|
204 | n/a | return self.emptyline() |
---|
205 | n/a | if cmd is None: |
---|
206 | n/a | return self.default(line) |
---|
207 | n/a | self.lastcmd = line |
---|
208 | n/a | if line == 'EOF' : |
---|
209 | n/a | self.lastcmd = '' |
---|
210 | n/a | if cmd == '': |
---|
211 | n/a | return self.default(line) |
---|
212 | n/a | else: |
---|
213 | n/a | try: |
---|
214 | n/a | func = getattr(self, 'do_' + cmd) |
---|
215 | n/a | except AttributeError: |
---|
216 | n/a | return self.default(line) |
---|
217 | n/a | return func(arg) |
---|
218 | n/a | |
---|
219 | n/a | def emptyline(self): |
---|
220 | n/a | """Called when an empty line is entered in response to the prompt. |
---|
221 | n/a | |
---|
222 | n/a | If this method is not overridden, it repeats the last nonempty |
---|
223 | n/a | command entered. |
---|
224 | n/a | |
---|
225 | n/a | """ |
---|
226 | n/a | if self.lastcmd: |
---|
227 | n/a | return self.onecmd(self.lastcmd) |
---|
228 | n/a | |
---|
229 | n/a | def default(self, line): |
---|
230 | n/a | """Called on an input line when the command prefix is not recognized. |
---|
231 | n/a | |
---|
232 | n/a | If this method is not overridden, it prints an error message and |
---|
233 | n/a | returns. |
---|
234 | n/a | |
---|
235 | n/a | """ |
---|
236 | n/a | self.stdout.write('*** Unknown syntax: %s\n'%line) |
---|
237 | n/a | |
---|
238 | n/a | def completedefault(self, *ignored): |
---|
239 | n/a | """Method called to complete an input line when no command-specific |
---|
240 | n/a | complete_*() method is available. |
---|
241 | n/a | |
---|
242 | n/a | By default, it returns an empty list. |
---|
243 | n/a | |
---|
244 | n/a | """ |
---|
245 | n/a | return [] |
---|
246 | n/a | |
---|
247 | n/a | def completenames(self, text, *ignored): |
---|
248 | n/a | dotext = 'do_'+text |
---|
249 | n/a | return [a[3:] for a in self.get_names() if a.startswith(dotext)] |
---|
250 | n/a | |
---|
251 | n/a | def complete(self, text, state): |
---|
252 | n/a | """Return the next possible completion for 'text'. |
---|
253 | n/a | |
---|
254 | n/a | If a command has not been entered, then complete against command list. |
---|
255 | n/a | Otherwise try to call complete_<command> to get list of completions. |
---|
256 | n/a | """ |
---|
257 | n/a | if state == 0: |
---|
258 | n/a | import readline |
---|
259 | n/a | origline = readline.get_line_buffer() |
---|
260 | n/a | line = origline.lstrip() |
---|
261 | n/a | stripped = len(origline) - len(line) |
---|
262 | n/a | begidx = readline.get_begidx() - stripped |
---|
263 | n/a | endidx = readline.get_endidx() - stripped |
---|
264 | n/a | if begidx>0: |
---|
265 | n/a | cmd, args, foo = self.parseline(line) |
---|
266 | n/a | if cmd == '': |
---|
267 | n/a | compfunc = self.completedefault |
---|
268 | n/a | else: |
---|
269 | n/a | try: |
---|
270 | n/a | compfunc = getattr(self, 'complete_' + cmd) |
---|
271 | n/a | except AttributeError: |
---|
272 | n/a | compfunc = self.completedefault |
---|
273 | n/a | else: |
---|
274 | n/a | compfunc = self.completenames |
---|
275 | n/a | self.completion_matches = compfunc(text, line, begidx, endidx) |
---|
276 | n/a | try: |
---|
277 | n/a | return self.completion_matches[state] |
---|
278 | n/a | except IndexError: |
---|
279 | n/a | return None |
---|
280 | n/a | |
---|
281 | n/a | def get_names(self): |
---|
282 | n/a | # This method used to pull in base class attributes |
---|
283 | n/a | # at a time dir() didn't do it yet. |
---|
284 | n/a | return dir(self.__class__) |
---|
285 | n/a | |
---|
286 | n/a | def complete_help(self, *args): |
---|
287 | n/a | commands = set(self.completenames(*args)) |
---|
288 | n/a | topics = set(a[5:] for a in self.get_names() |
---|
289 | n/a | if a.startswith('help_' + args[0])) |
---|
290 | n/a | return list(commands | topics) |
---|
291 | n/a | |
---|
292 | n/a | def do_help(self, arg): |
---|
293 | n/a | 'List available commands with "help" or detailed help with "help cmd".' |
---|
294 | n/a | if arg: |
---|
295 | n/a | # XXX check arg syntax |
---|
296 | n/a | try: |
---|
297 | n/a | func = getattr(self, 'help_' + arg) |
---|
298 | n/a | except AttributeError: |
---|
299 | n/a | try: |
---|
300 | n/a | doc=getattr(self, 'do_' + arg).__doc__ |
---|
301 | n/a | if doc: |
---|
302 | n/a | self.stdout.write("%s\n"%str(doc)) |
---|
303 | n/a | return |
---|
304 | n/a | except AttributeError: |
---|
305 | n/a | pass |
---|
306 | n/a | self.stdout.write("%s\n"%str(self.nohelp % (arg,))) |
---|
307 | n/a | return |
---|
308 | n/a | func() |
---|
309 | n/a | else: |
---|
310 | n/a | names = self.get_names() |
---|
311 | n/a | cmds_doc = [] |
---|
312 | n/a | cmds_undoc = [] |
---|
313 | n/a | help = {} |
---|
314 | n/a | for name in names: |
---|
315 | n/a | if name[:5] == 'help_': |
---|
316 | n/a | help[name[5:]]=1 |
---|
317 | n/a | names.sort() |
---|
318 | n/a | # There can be duplicates if routines overridden |
---|
319 | n/a | prevname = '' |
---|
320 | n/a | for name in names: |
---|
321 | n/a | if name[:3] == 'do_': |
---|
322 | n/a | if name == prevname: |
---|
323 | n/a | continue |
---|
324 | n/a | prevname = name |
---|
325 | n/a | cmd=name[3:] |
---|
326 | n/a | if cmd in help: |
---|
327 | n/a | cmds_doc.append(cmd) |
---|
328 | n/a | del help[cmd] |
---|
329 | n/a | elif getattr(self, name).__doc__: |
---|
330 | n/a | cmds_doc.append(cmd) |
---|
331 | n/a | else: |
---|
332 | n/a | cmds_undoc.append(cmd) |
---|
333 | n/a | self.stdout.write("%s\n"%str(self.doc_leader)) |
---|
334 | n/a | self.print_topics(self.doc_header, cmds_doc, 15,80) |
---|
335 | n/a | self.print_topics(self.misc_header, list(help.keys()),15,80) |
---|
336 | n/a | self.print_topics(self.undoc_header, cmds_undoc, 15,80) |
---|
337 | n/a | |
---|
338 | n/a | def print_topics(self, header, cmds, cmdlen, maxcol): |
---|
339 | n/a | if cmds: |
---|
340 | n/a | self.stdout.write("%s\n"%str(header)) |
---|
341 | n/a | if self.ruler: |
---|
342 | n/a | self.stdout.write("%s\n"%str(self.ruler * len(header))) |
---|
343 | n/a | self.columnize(cmds, maxcol-1) |
---|
344 | n/a | self.stdout.write("\n") |
---|
345 | n/a | |
---|
346 | n/a | def columnize(self, list, displaywidth=80): |
---|
347 | n/a | """Display a list of strings as a compact set of columns. |
---|
348 | n/a | |
---|
349 | n/a | Each column is only as wide as necessary. |
---|
350 | n/a | Columns are separated by two spaces (one was not legible enough). |
---|
351 | n/a | """ |
---|
352 | n/a | if not list: |
---|
353 | n/a | self.stdout.write("<empty>\n") |
---|
354 | n/a | return |
---|
355 | n/a | |
---|
356 | n/a | nonstrings = [i for i in range(len(list)) |
---|
357 | n/a | if not isinstance(list[i], str)] |
---|
358 | n/a | if nonstrings: |
---|
359 | n/a | raise TypeError("list[i] not a string for i in %s" |
---|
360 | n/a | % ", ".join(map(str, nonstrings))) |
---|
361 | n/a | size = len(list) |
---|
362 | n/a | if size == 1: |
---|
363 | n/a | self.stdout.write('%s\n'%str(list[0])) |
---|
364 | n/a | return |
---|
365 | n/a | # Try every row count from 1 upwards |
---|
366 | n/a | for nrows in range(1, len(list)): |
---|
367 | n/a | ncols = (size+nrows-1) // nrows |
---|
368 | n/a | colwidths = [] |
---|
369 | n/a | totwidth = -2 |
---|
370 | n/a | for col in range(ncols): |
---|
371 | n/a | colwidth = 0 |
---|
372 | n/a | for row in range(nrows): |
---|
373 | n/a | i = row + nrows*col |
---|
374 | n/a | if i >= size: |
---|
375 | n/a | break |
---|
376 | n/a | x = list[i] |
---|
377 | n/a | colwidth = max(colwidth, len(x)) |
---|
378 | n/a | colwidths.append(colwidth) |
---|
379 | n/a | totwidth += colwidth + 2 |
---|
380 | n/a | if totwidth > displaywidth: |
---|
381 | n/a | break |
---|
382 | n/a | if totwidth <= displaywidth: |
---|
383 | n/a | break |
---|
384 | n/a | else: |
---|
385 | n/a | nrows = len(list) |
---|
386 | n/a | ncols = 1 |
---|
387 | n/a | colwidths = [0] |
---|
388 | n/a | for row in range(nrows): |
---|
389 | n/a | texts = [] |
---|
390 | n/a | for col in range(ncols): |
---|
391 | n/a | i = row + nrows*col |
---|
392 | n/a | if i >= size: |
---|
393 | n/a | x = "" |
---|
394 | n/a | else: |
---|
395 | n/a | x = list[i] |
---|
396 | n/a | texts.append(x) |
---|
397 | n/a | while texts and not texts[-1]: |
---|
398 | n/a | del texts[-1] |
---|
399 | n/a | for col in range(len(texts)): |
---|
400 | n/a | texts[col] = texts[col].ljust(colwidths[col]) |
---|
401 | n/a | self.stdout.write("%s\n"%str(" ".join(texts))) |
---|