cmd.py 15 KB

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