blob: 857bed127b749f253ac1b3b8b378e8af7427b99c [file] [log] [blame]
Guido van Rossumb53e6781992-01-24 01:12:17 +00001# A generic class to build line-oriented command interpreters
2
3import string
4import sys
5import linecache
6
7PROMPT = '(Cmd) '
8IDENTCHARS = string.letters + string.digits + '_'
9
10class Cmd:
Guido van Rossum9b3bc711993-06-20 21:02:22 +000011
12 def __init__(self):
Guido van Rossumb53e6781992-01-24 01:12:17 +000013 self.prompt = PROMPT
14 self.identchars = IDENTCHARS
15 self.lastcmd = ''
Guido van Rossumb53e6781992-01-24 01:12:17 +000016
17 def cmdloop(self):
18 stop = None
19 while not stop:
20 try:
21 line = raw_input(self.prompt)
22 except EOFError:
23 line = 'EOF'
24 stop = self.onecmd(line)
25
26 def onecmd(self, line):
27 line = string.strip(line)
28 if not line:
29 line = self.lastcmd
Guido van Rossumb53e6781992-01-24 01:12:17 +000030 else:
31 self.lastcmd = line
32 i, n = 0, len(line)
33 while i < n and line[i] in self.identchars: i = i+1
34 cmd, arg = line[:i], string.strip(line[i:])
35 if cmd == '':
36 return self.default(line)
37 else:
38 try:
Guido van Rossumc629d341992-11-05 10:43:02 +000039 func = getattr(self, 'do_' + cmd)
Guido van Rossumb53e6781992-01-24 01:12:17 +000040 except AttributeError:
41 return self.default(line)
42 return func(arg)
43
44 def default(self, line):
45 print '*** Unknown syntax:', line
46
47 def do_help(self, arg):
48 if arg:
49 # XXX check arg syntax
50 try:
Guido van Rossumc629d341992-11-05 10:43:02 +000051 func = getattr(self, 'help_' + arg)
Guido van Rossumb53e6781992-01-24 01:12:17 +000052 except:
53 print '*** No help on', `arg`
54 return
55 func()
56 else:
Guido van Rossum7ef2a1d1998-05-22 14:11:57 +000057 names = dir(self.__class__)
Guido van Rossumb6775db1994-08-01 11:34:53 +000058 cmds_doc = []
59 cmds_undoc = []
60 help = {}
61 for name in names:
62 if name[:5] == 'help_':
63 help[name[5:]]=1
Guido van Rossumb53e6781992-01-24 01:12:17 +000064 for name in names:
65 if name[:3] == 'do_':
Guido van Rossumb6775db1994-08-01 11:34:53 +000066 cmd=name[3:]
67 if help.has_key(cmd):
68 cmds_doc.append(cmd)
69 del help[cmd]
70 else:
71 cmds_undoc.append(cmd)
72 print
73 self.print_topics("Documented commands (type help " \
74 "<topic>):",cmds_doc, 15, 80)
75 self.print_topics("Miscellaneous help topics:",
76 help.keys(), 15, 80)
77 self.print_topics("Undocumented commands:",
78 cmds_undoc, 15, 80)
79
80 def print_topics(self, header, cmds, cmdlen, maxcol):
81 if cmds:
82 print header;
83 print "="*len(header)
84 (cmds_per_line,junk)=divmod(maxcol,cmdlen)
85 col=cmds_per_line
86 for cmd in cmds:
87 if col==0: print
88 print (("%-"+`cmdlen`+"s") % cmd),
89 col = (col+1) % cmds_per_line
90 print "\n"