comparison cmd2.py @ 67:a78dff1e7bca

prelim tests work; weirdness with xclip and shift-ins
author catherine@Elli.myhome.westell.com
date Mon, 23 Jun 2008 17:37:10 -0400
parents f373aaa2390c
children e06961ebd035
comparison
equal deleted inserted replaced
66:f373aaa2390c 67:a78dff1e7bca
148 processed[0] = pyparsing.Literal(processed[0]) 148 processed[0] = pyparsing.Literal(processed[0])
149 processed = reduce(lambda x, y: x ^ y, processed) 149 processed = reduce(lambda x, y: x ^ y, processed)
150 processed.ignore(pyparsing.sglQuotedString) 150 processed.ignore(pyparsing.sglQuotedString)
151 processed.ignore(pyparsing.dblQuotedString) 151 processed.ignore(pyparsing.dblQuotedString)
152 pattern = pyparsing.SkipTo(processed) + processed + pyparsing.restOfLine 152 pattern = pyparsing.SkipTo(processed) + processed + pyparsing.restOfLine
153 def parser(txt): 153 def parser(self, txt):
154 result = pattern.searchString(txt) 154 result = pattern.searchString(txt)
155 if result: 155 if result:
156 return result[0][0], result[0][1:-1], result[0][-1] 156 return result[0][0].strip(), result[0][1:-1], result[0][-1].strip()
157 else: 157 else:
158 return None 158 return None
159 return parser 159 return parser
160 160
161
162
161 class Cmd(cmd.Cmd): 163 class Cmd(cmd.Cmd):
162 caseInsensitive = True 164 caseInsensitive = True
163 multilineCommands = [] 165 multilineCommands = []
164 continuationPrompt = '> ' 166 continuationPrompt = '> '
165 shortcuts = {'?': 'help', '!': 'shell', '@': 'load'} 167 shortcuts = {'?': 'help', '!': 'shell', '@': 'load'}
205 207
206 def do_shortcuts(self, args): 208 def do_shortcuts(self, args):
207 """Lists single-key shortcuts available.""" 209 """Lists single-key shortcuts available."""
208 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in self.shortcuts.items()) 210 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in self.shortcuts.items())
209 self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result)) 211 self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result))
210 212
211 commmand_terminator_finder = punctuationParser(terminators) 213 commmand_terminator_finder = punctuationParser(terminators)
212 output_destination_finder = punctuationParser(['>>', '>']) 214 output_destination_finder = punctuationParser(['>>', '>'])
213 input_source_finder = punctuationParser(['<']) 215 input_source_finder = punctuationParser(['<'])
214 pipe_destination_finder = punctuationParser(['|']) 216 pipe_destination_finder = punctuationParser(['|'])
217 def strip_terminators(self, txt):
218 termination = self.commmand_terminator_finder(txt)
219 if termination:
220 txt = termination[0]
221 return txt
215 222
216 def extractCommand(self, statement): 223 def extractCommand(self, statement):
217 try: 224 try:
218 (command, args) = statement.split(None,1) 225 (command, args) = statement.split(None,1)
219 except ValueError: 226 except ValueError:
239 This may be overridden, but should not normally need to be; 246 This may be overridden, but should not normally need to be;
240 see the precmd() and postcmd() methods for useful execution hooks. 247 see the precmd() and postcmd() methods for useful execution hooks.
241 The return value is a flag indicating whether interpretation of 248 The return value is a flag indicating whether interpretation of
242 commands by the interpreter should stop. 249 commands by the interpreter should stop.
243 250
244 """ 251 """
245 command, args = self.extractCommand(line) 252 command, args = self.extractCommand(line)
246 statement = originalStatement = ' '.join([command, args]) 253 statement = originalStatement = ' '.join([command, args])
247 if (not assumeComplete) and (command in self.multilineCommands): 254 if (not assumeComplete) and (command in self.multilineCommands):
248 statement = self.completedStatement(statement) 255 statement = self.completedStatement(statement)
249 statekeeper = None 256 statekeeper = None
257 else: 264 else:
258 statement = getPasteBuffer() 265 statement = getPasteBuffer()
259 266
260 pipeTo = self.pipe_destination_finder(statement) 267 pipeTo = self.pipe_destination_finder(statement)
261 if pipeTo: 268 if pipeTo:
262 statement, pipeTo = pipeTo[0], [-1] 269 statement, pipeTo = pipeTo[0], pipeTo[-1]
263 statekeeper = Statekeeper(self, ('stdout',)) 270 statekeeper = Statekeeper(self, ('stdout',))
264 pipeTo = subprocess.Popen(PipeTo, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) 271 pipeTo = subprocess.Popen(pipeTo, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
265 self.stdout = redirect.stdin 272 self.stdout = pipeTo.stdin
266 else: # can't pipe output AND send it to a file 273 else: # can't pipe output AND send it to a file
267 outputTo = self.outputTo_finder(statement) 274 outputTo = self.output_destination_finder(statement)
268 if outputTo: 275 if outputTo:
269 statement, destination = outputTo[0], outputTo[-1] 276 statement, destination = outputTo[0], outputTo[-1]
270 statekeeper = Statekeeper(self, ('stdout',)) 277 statekeeper = Statekeeper(self, ('stdout',))
271 mode = ((output[1] == '>>') and 'a') or 'w' 278 mode = ((outputTo[1][0] == '>>') and 'a') or 'w'
272 if destination: 279 if destination:
273 self.stdout = open(destination, mode) 280 self.stdout = open(destination, mode)
274 else: 281 else:
275 self.stdout = tempfile.TemporaryFile() 282 self.stdout = tempfile.TemporaryFile()
276 if mode == 'a': 283 if mode == 'a':
280 try: 287 try:
281 if command not in self.excludeFromHistory: 288 if command not in self.excludeFromHistory:
282 self.history.append(originalStatement) 289 self.history.append(originalStatement)
283 finally: 290 finally:
284 if statekeeper: 291 if statekeeper:
285 if outputTo and not destination: 292 if pipeTo:
293 for result in pipeTo.communicate():
294 statekeeper.stdout.write(result or '')
295 elif outputTo and not destination:
286 self.stdout.seek(0) 296 self.stdout.seek(0)
287 writeToPasteBuffer(self.stdout.read()) 297 writeToPasteBuffer(self.stdout.read())
288 elif pipeTo: # uh-oh. HUH?
289 for result in redirect.communicate():
290 statekeeper.stdout.write(result or '')
291 self.stdout.close() 298 self.stdout.close()
292 statekeeper.restore() 299 statekeeper.restore()
293 300
294 return stop 301 return stop
295 302
375 shortcut = self.shortcuts.get(line[0]) 382 shortcut = self.shortcuts.get(line[0])
376 if shortcut and hasattr(self, 'do_%s' % shortcut): 383 if shortcut and hasattr(self, 'do_%s' % shortcut):
377 line = '%s %s' % (shortcut, line[1:]) 384 line = '%s %s' % (shortcut, line[1:])
378 i, n = 0, len(line) 385 i, n = 0, len(line)
379 while i < n and line[i] in self.identchars: i = i+1 386 while i < n and line[i] in self.identchars: i = i+1
380 cmd, arg = line[:i], line[i:].strip().strip(self.terminators) 387 cmd, arg = line[:i], line[i:].strip()
388 arg = self.strip_terminators(arg)
381 return cmd, arg, line 389 return cmd, arg, line
382 390
383 def showParam(self, param): 391 def showParam(self, param):
384 param = self.clean(param) 392 param = self.clean(param)
385 if param in self.settable: 393 if param in self.settable:
405 paramName, val = arg.split(None, 1) 413 paramName, val = arg.split(None, 1)
406 paramName = self.clean(paramName) 414 paramName = self.clean(paramName)
407 if paramName not in self.settable: 415 if paramName not in self.settable:
408 raise NotSettableError 416 raise NotSettableError
409 currentVal = getattr(self, paramName) 417 currentVal = getattr(self, paramName)
410 val = cast(currentVal, val.strip(self.terminators)) 418 val = cast(currentVal, self.strip_terminators(val))
411 setattr(self, paramName, val) 419 setattr(self, paramName, val)
412 self.stdout.write('%s - was: %s\nnow: %s\n' % (paramName, currentVal, val)) 420 self.stdout.write('%s - was: %s\nnow: %s\n' % (paramName, currentVal, val))
413 except (ValueError, AttributeError, NotSettableError), e: 421 except (ValueError, AttributeError, NotSettableError), e:
414 self.do_show(arg) 422 self.do_show(arg)
415 423