comparison cmd2.py @ 26:bb3fb24b6f5f

settables ironed out
author devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
date Wed, 19 Dec 2007 16:10:01 -0500
parents c99853267a44
children ca6f34be3397
comparison
equal deleted inserted replaced
25:c99853267a44 26:bb3fb24b6f5f
18 multilineCommands = [] 18 multilineCommands = []
19 continuationPrompt = '> ' 19 continuationPrompt = '> '
20 shortcuts = {'?': 'help', '!': 'shell', '@': 'load'} 20 shortcuts = {'?': 'help', '!': 'shell', '@': 'load'}
21 excludeFromHistory = '''run r list l history hi ed li eof'''.split() 21 excludeFromHistory = '''run r list l history hi ed li eof'''.split()
22 defaultExtension = 'txt' 22 defaultExtension = 'txt'
23 settable = [] 23 settable = ['prompt', 'continuationPrompt']
24 terminators = r';\n' 24 terminators = ';\n'
25 def do_cmdenvironment(self, args): 25 def do_cmdenvironment(self, args):
26 self.stdout.write(""" 26 self.stdout.write("""
27 Commands are %(casesensitive)scase-sensitive. 27 Commands are %(casesensitive)scase-sensitive.
28 Commands may be terminated with: %(terminators)s 28 Commands may be terminated with: %(terminators)s
29 Settable parameters: %(settable)s 29 Settable parameters: %(settable)s
92 92
93 def do_EOF(self, arg): 93 def do_EOF(self, arg):
94 return True 94 return True
95 do_eof = do_EOF 95 do_eof = do_EOF
96 96
97 statementEndPattern = re.compile(r'[%s]\s*$' % self.terminators) 97 statementEndPattern = re.compile(r'[%s]\s*$' % terminators)
98 def statementHasEnded(self, lines): 98 def statementHasEnded(self, lines):
99 return bool(self.statementEndPattern.search(lines)) 99 return bool(self.statementEndPattern.search(lines))
100 100
101 def clean(self, s): 101 def clean(self, s):
102 """cleans up a string""" 102 """cleans up a string"""
115 shortcut = self.shortcuts.get(line[0]) 115 shortcut = self.shortcuts.get(line[0])
116 if shortcut and hasattr(self, 'do_%s' % shortcut): 116 if shortcut and hasattr(self, 'do_%s' % shortcut):
117 line = '%s %s' % (shortcut, line[1:]) 117 line = '%s %s' % (shortcut, line[1:])
118 i, n = 0, len(line) 118 i, n = 0, len(line)
119 while i < n and line[i] in self.identchars: i = i+1 119 while i < n and line[i] in self.identchars: i = i+1
120 cmd, arg = line[:i], line[i:].strip() 120 cmd, arg = line[:i], line[i:].strip().strip(self.terminators)
121 return cmd, arg, line 121 return cmd, arg, line
122 122
123 def showParam(self, param): 123 def showParam(self, param):
124 param = self.clean(param) 124 param = self.clean(param)
125 if param in self.settable: 125 if param in self.settable:
131 if arg.strip(): 131 if arg.strip():
132 self.showParam(arg) 132 self.showParam(arg)
133 else: 133 else:
134 for param in self.settable: 134 for param in self.settable:
135 self.showParam(param) 135 self.showParam(param)
136
137 def cast(self, current, new):
138 typ = type(current)
139 if typ == bool:
140 new = new.lower()
141 try:
142 if (new=='on') or (new[0] in ('y','t')):
143 return True
144 return False
145 except TypeError:
146 None
147 try:
148 return typ(new)
149 except:
150 print "Problem setting parameter (now %s) to %s; incorrect type?" % (current, new)
151 return current
152 136
153 def do_set(self, arg): 137 def do_set(self, arg):
154 'Sets a parameter' 138 'Sets a parameter'
155 try: 139 try:
156 paramName, val = arg.split(None, 1) 140 paramName, val = arg.split(None, 1)
157 paramName = self.clean(paramName) 141 paramName = self.clean(paramName)
158 if paramName not in self.settable: 142 if paramName not in self.settable:
159 raise NotSettableError 143 raise NotSettableError
160 currentVal = getattr(self, paramName) 144 currentVal = getattr(self, paramName)
161 val = self.cast(currentVal, val.strip(self.terminators)) 145 val = cast(currentVal, val.strip(self.terminators))
162 setattr(self, paramName, val) 146 setattr(self, paramName, val)
163 self.stdout.write(paramName, ' - was: %s\nnow: %s\n' % (currentVal, val)) 147 self.stdout.write('%s - was: %s\nnow: %s\n' % (paramName, currentVal, val))
164 except ValueError, AttributeError, NotSettableError: 148 except (ValueError, AttributeError, NotSettableError):
165 self.do_show(arg) 149 self.do_show(arg)
166 150
167 def do_shell(self, arg): 151 def do_shell(self, arg):
168 'execute a command as if at the OS prompt.' 152 'execute a command as if at the OS prompt.'
169 os.system(arg) 153 os.system(arg)
204 except: 188 except:
205 pass 189 pass
206 do_hi = do_history 190 do_hi = do_history
207 do_l = do_list 191 do_l = do_list
208 do_li = do_list 192 do_li = do_list
209
210 def breakupStatements(self, txt):
211 """takes text that may include multiple statements and
212 breaks it into a list of individual statements."""
213 result = ['']
214 for line in txt.splitlines():
215 result[-1] += line
216 if self.statementHasEnded(result[-1]):
217 result.append('')
218 193
219 def do_load(self, fname): 194 def do_load(self, fname):
220 """Runs command(s) from a file.""" 195 """Runs command(s) from a file."""
221 keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt','continuationPrompt')) 196 keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt','continuationPrompt'))
222 try: 197 try:
275 return [itm for itm in self if isin(itm)] 250 return [itm for itm in self if isin(itm)]
276 251
277 class NotSettableError(Exception): 252 class NotSettableError(Exception):
278 None 253 None
279 254
255 def cast(current, new):
256 """Tries to force a new value into the same type as the current."""
257 typ = type(current)
258 print type(new)
259 if typ == bool:
260 new = new.lower()
261 print new
262 try:
263 print new == 'on'
264 if (new=='on') or (new[0] in ('y','t')):
265 return True
266 try:
267 return bool(int(new))
268 except ValueError:
269 pass
270 return False
271 except TypeError:
272 pass
273 try:
274 return typ(new)
275 except:
276 print "Problem setting parameter (now %s) to %s; incorrect type?" % (current, new)
277 return current
278
280 class Statekeeper(object): 279 class Statekeeper(object):
281 def __init__(self, obj, attribs): 280 def __init__(self, obj, attribs):
282 self.obj = obj 281 self.obj = obj
283 self.attribs = attribs 282 self.attribs = attribs
284 self.save() 283 self.save()