cmd.py 15 KB

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