comparison cmd2.py @ 16:2776755a3a7e

beginning separation of cmd2
author devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
date Wed, 19 Dec 2007 10:28:01 -0500
parents
children 25e908abf199
comparison
equal deleted inserted replaced
15:9c7df9f825a1 16:2776755a3a7e
1 import cmd, re
2
3 class HistoryItem(str):
4 def __init__(self, instr):
5 str.__init__(self, instr)
6 self.lowercase = self.lower()
7 self.idx = None
8 def pr(self):
9 print '-------------------------[%d]' % (self.idx)
10 print self
11
12 class History(list):
13 rangeFrom = re.compile(r'^([\d])+\s*\-$')
14 def append(self, new):
15 new = HistoryItem(new)
16 list.append(self, new)
17 new.idx = len(self)
18 def extend(self, new):
19 for n in new:
20 self.append(n)
21 def get(self, getme):
22 try:
23 getme = int(getme)
24 if getme < 0:
25 return self[:(-1 * getme)]
26 else:
27 return [self[getme-1]]
28 except IndexError:
29 return []
30 except (ValueError, TypeError):
31 getme = getme.strip()
32 mtch = self.rangeFrom.search(getme)
33 if mtch:
34 return self[(int(mtch.group(1))-1):]
35 if getme.startswith(r'/') and getme.endswith(r'/'):
36 finder = re.compile(getme[1:-1], re.DOTALL | re.MULTILINE | re.IGNORECASE)
37 def isin(hi):
38 return finder.search(hi)
39 else:
40 def isin(hi):
41 return (getme.lower() in hi.lowercase)
42 return [itm for itm in self if isin(itm)]
43
44 class Cmd(cmd.Cmd):
45 def __init__(self, *args, **kwargs):
46 cmd.Cmd.__init__(self, *args, **kwargs)
47 self.history = History()
48 self.excludeFromHistory = '''run r list l history hi ed li'''.split()
49
50 def postcmd(self, stop, line):
51 """Hook method executed just after a command dispatch is finished."""
52 try:
53 command = line.split(None,1)[0].lower()
54 if command not in self.excludeFromHistory:
55 self.history.append(line)
56 finally:
57 return stop
58
59 def do_history(self, arg):
60 """history [arg]: lists past commands issued
61
62 no arg -> list all
63 arg is integer -> list one history item, by index
64 arg is string -> string search
65 arg is /enclosed in forward-slashes/ -> regular expression search
66 """
67 if arg:
68 history = self.history.get(arg)
69 else:
70 history = self.history
71 for hi in history:
72 hi.pr()
73 def last_matching(self, arg):
74 try:
75 if arg:
76 return self.history.get(arg)[-1]
77 else:
78 return self.history[-1]
79 except:
80 return None
81 def do_list(self, arg):
82 """list [arg]: lists last command issued
83
84 no arg -> list absolute last
85 arg is integer -> list one history item, by index
86 - arg, arg - (integer) -> list up to or after #arg
87 arg is string -> list last command matching string search
88 arg is /enclosed in forward-slashes/ -> regular expression search
89 """
90 try:
91 self.last_matching(arg).pr()
92 except:
93 pass
94 do_hi = do_history
95 do_l = do_list
96 do_li = do_list
97