comparison cmd2.py @ 30:2739250177ed

load fixed?
author devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
date Fri, 21 Dec 2007 14:00:11 -0500
parents a6f68b25ae16
children 5e2f6ec2e383
comparison
equal deleted inserted replaced
29:a6f68b25ae16 30:2739250177ed
7 Load commands from file 7 Load commands from file
8 Settable environment parameters 8 Settable environment parameters
9 9
10 still to do: 10 still to do:
11 edit 11 edit
12 run
12 > 13 >
13 """ 14 """
14 import cmd, re, os 15 import cmd, re, os
15 16
16 class Cmd(cmd.Cmd): 17 class Cmd(cmd.Cmd):
20 shortcuts = {'?': 'help', '!': 'shell', '@': 'load'} 21 shortcuts = {'?': 'help', '!': 'shell', '@': 'load'}
21 excludeFromHistory = '''run r list l history hi ed li eof'''.split() 22 excludeFromHistory = '''run r list l history hi ed li eof'''.split()
22 defaultExtension = 'txt' 23 defaultExtension = 'txt'
23 defaultFileName = 'command.txt' 24 defaultFileName = 'command.txt'
24 editor = os.environ.get('EDITOR') or '' 25 editor = os.environ.get('EDITOR') or ''
25 settable = ['prompt', 'continuationPrompt', 'defaultFileName', 'editor'] 26 settable = ['prompt', 'continuationPrompt', 'defaultFileName', 'editor', 'caseInsensitive']
26 terminators = ';\n' 27 terminators = ';\n'
27 def do_cmdenvironment(self, args): 28 def do_cmdenvironment(self, args):
28 self.stdout.write(""" 29 self.stdout.write("""
29 Commands are %(casesensitive)scase-sensitive. 30 Commands are %(casesensitive)scase-sensitive.
30 Commands may be terminated with: %(terminators)s 31 Commands may be terminated with: %(terminators)s
66 return stop 67 return stop
67 68
68 def finishStatement(self, firstline): 69 def finishStatement(self, firstline):
69 statement = firstline 70 statement = firstline
70 while not self.statementHasEnded(statement): 71 while not self.statementHasEnded(statement):
71 statement = '%s\n%s' % (statement, self.pseudo_raw_input(self.continuationPrompt)) 72 inp = self.pseudo_raw_input(self.continuationPrompt)
73 statement = '%s\n%s' % (statement, inp)
72 return statement 74 return statement
73 # assembling a list of lines and joining them at the end would be faster, 75 # assembling a list of lines and joining them at the end would be faster,
74 # but statementHasEnded needs a string arg; anyway, we're getting 76 # but statementHasEnded needs a string arg; anyway, we're getting
75 # user input and users are slow. 77 # user input and users are slow.
76 78
94 96
95 def do_EOF(self, arg): 97 def do_EOF(self, arg):
96 return True 98 return True
97 do_eof = do_EOF 99 do_eof = do_EOF
98 100
99 statementEndPattern = re.compile(r'[%s]\s*$' % terminators) 101 statementEndPattern = re.compile(r'([%s]\s*)|(EOF)$' % terminators)
100 def statementHasEnded(self, lines): 102 def statementHasEnded(self, lines):
101 return bool(self.statementEndPattern.search(lines)) 103 return bool(self.statementEndPattern.search(lines))
102 104
103 def clean(self, s): 105 def clean(self, s):
104 """cleans up a string""" 106 """cleans up a string"""
145 raise NotSettableError 147 raise NotSettableError
146 currentVal = getattr(self, paramName) 148 currentVal = getattr(self, paramName)
147 val = cast(currentVal, val.strip(self.terminators)) 149 val = cast(currentVal, val.strip(self.terminators))
148 setattr(self, paramName, val) 150 setattr(self, paramName, val)
149 self.stdout.write('%s - was: %s\nnow: %s\n' % (paramName, currentVal, val)) 151 self.stdout.write('%s - was: %s\nnow: %s\n' % (paramName, currentVal, val))
150 except (ValueError, AttributeError, NotSettableError): 152 except (ValueError, AttributeError, NotSettableError), e:
151 self.do_show(arg) 153 self.do_show(arg)
152 154
153 def do_shell(self, arg): 155 def do_shell(self, arg):
154 'execute a command as if at the OS prompt.' 156 'execute a command as if at the OS prompt.'
155 os.system(arg) 157 os.system(arg)
194 do_li = do_list 196 do_li = do_list
195 197
196 def do_ed(self, arg): 198 def do_ed(self, arg):
197 'ed [N]: brings up SQL from N commands ago in text editor, and puts result in SQL buffer.' 199 'ed [N]: brings up SQL from N commands ago in text editor, and puts result in SQL buffer.'
198 if not self.editor: 200 if not self.editor:
199 self.do_show('editor') 201 print "please use 'set editor' to specify your text editing program of choice."
200 return 202 return
201 buffer = self.last_matching(arg) 203 buffer = self.last_matching(arg)
202 if not buffer: 204 if not buffer:
203 print 'Nothing appropriate in buffer to edit.' 205 print 'Nothing appropriate in buffer to edit.'
204 return 206 return
205 f = open(self.defaultFileName, 'w') 207 f = open(self.defaultFileName, 'w')
206 f.write(buffer) 208 f.write(buffer)
207 f.close() 209 f.close()
208 os.system('%s %s' % (self.editor, self.defaultFileName)) 210 os.system('%s %s' % (self.editor, self.defaultFileName))
209 self.load(self.defaultFileName) 211 self.do_load(self.defaultFileName)
210 do_edit = do_ed 212 do_edit = do_ed
211 213
212 def do_save(self, fname=None): 214 def do_save(self, fname=None):
213 """Saves most recent command to a file.""" 215 """Saves most recent command to a file."""
214 216
281 def isin(hi): 283 def isin(hi):
282 return (getme.lower() in hi.lowercase) 284 return (getme.lower() in hi.lowercase)
283 return [itm for itm in self if isin(itm)] 285 return [itm for itm in self if isin(itm)]
284 286
285 class NotSettableError(Exception): 287 class NotSettableError(Exception):
286 None 288 pass
287 289
288 def cast(current, new): 290 def cast(current, new):
289 """Tries to force a new value into the same type as the current.""" 291 """Tries to force a new value into the same type as the current."""
290 typ = type(current) 292 typ = type(current)
291 print type(new)
292 if typ == bool: 293 if typ == bool:
293 new = new.lower() 294 try:
294 print new 295 return bool(int(new))
295 try: 296 except ValueError, TypeError:
296 print new == 'on' 297 pass
297 if (new=='on') or (new[0] in ('y','t')): 298 try:
298 return True 299 new = new.lower()
299 try: 300 except:
300 return bool(int(new)) 301 pass
301 except ValueError: 302 if (new=='on') or (new[0] in ('y','t')):
302 pass 303 return True
304 if (new=='off') or (new[0] in ('n','f')):
303 return False 305 return False
304 except TypeError: 306 else:
307 try:
308 return typ(new)
309 except:
305 pass 310 pass
306 try: 311 print "Problem setting parameter (now %s) to %s; incorrect type?" % (current, new)
307 return typ(new) 312 return current
308 except:
309 print "Problem setting parameter (now %s) to %s; incorrect type?" % (current, new)
310 return current
311 313
312 class Statekeeper(object): 314 class Statekeeper(object):
313 def __init__(self, obj, attribs): 315 def __init__(self, obj, attribs):
314 self.obj = obj 316 self.obj = obj
315 self.attribs = attribs 317 self.attribs = attribs