blob: d28e3932861e7d6b7ce18e3ca0c85aee93f782f8 [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:
11
12 def init(self):
13 self.prompt = PROMPT
14 self.identchars = IDENTCHARS
15 self.lastcmd = ''
16 return self
17
18 def cmdloop(self):
19 stop = None
20 while not stop:
21 try:
22 line = raw_input(self.prompt)
23 except EOFError:
24 line = 'EOF'
25 stop = self.onecmd(line)
26
27 def onecmd(self, line):
28 line = string.strip(line)
29 if not line:
30 line = self.lastcmd
31 print line
32 else:
33 self.lastcmd = line
34 i, n = 0, len(line)
35 while i < n and line[i] in self.identchars: i = i+1
36 cmd, arg = line[:i], string.strip(line[i:])
37 if cmd == '':
38 return self.default(line)
39 else:
40 try:
41 func = eval('self.do_' + cmd)
42 except AttributeError:
43 return self.default(line)
44 return func(arg)
45
46 def default(self, line):
47 print '*** Unknown syntax:', line
48
49 def do_help(self, arg):
50 if arg:
51 # XXX check arg syntax
52 try:
53 func = eval('self.help_' + arg)
54 except:
55 print '*** No help on', `arg`
56 return
57 func()
58 else:
59 import getattr
60 names = getattr.dir(self)
61 cmds = []
62 for name in names:
63 if name[:3] == 'do_':
64 cmds.append(name[3:])
65 print cmds