summaryrefslogtreecommitdiffstats
path: root/Lib/cmd.py
blob: e07019f2a8b72f14e7dfed463197141df2e31cd4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# A generic class to build line-oriented command interpreters

import string
import sys
import linecache

PROMPT = '(Cmd) '
IDENTCHARS = string.letters + string.digits + '_'

class Cmd:
	
	def init(self):
		self.prompt = PROMPT
		self.identchars = IDENTCHARS
		self.lastcmd = ''
		return self

	def cmdloop(self):
		stop = None
		while not stop:
			try:
				line = raw_input(self.prompt)
			except EOFError:
				line = 'EOF'
			stop = self.onecmd(line)

	def onecmd(self, line):
		line = string.strip(line)
		if not line:
			line = self.lastcmd
		else:
			self.lastcmd = line
		i, n = 0, len(line)
		while i < n and line[i] in self.identchars: i = i+1
		cmd, arg = line[:i], string.strip(line[i:])
		if cmd == '':
			return self.default(line)
		else:
			try:
				func = eval('self.do_' + cmd)
			except AttributeError:
				return self.default(line)
			return func(arg)

	def default(self, line):
		print '*** Unknown syntax:', line

	def do_help(self, arg):
		if arg:
			# XXX check arg syntax
			try:
				func = eval('self.help_' + arg)
			except:
				print '*** No help on', `arg`
				return
			func()
		else:
			import newdir
			names = newdir.dir(self)
			cmds = []
			for name in names:
				if name[:3] == 'do_':
					cmds.append(name[3:])
			print cmds