comparison cmd2.py @ 154:606ad25c7f7e

new experiment with ignore?
author catherine@dellzilla
date Fri, 21 Nov 2008 15:39:42 -0500
parents 5c5c458a6b70
children 8ba5127167f5
comparison
equal deleted inserted replaced
153:5c5c458a6b70 154:606ad25c7f7e
145 result['upToIncluding'] = s[:stop] 145 result['upToIncluding'] = s[:stop]
146 except StopIteration: 146 except StopIteration:
147 result = pyparsing.ParseResults('') 147 result = pyparsing.ParseResults('')
148 result['before'] = s 148 result['before'] = s
149 return result 149 return result
150 150
151
152 def replaceInput(source):
153 if source:
154 newinput = open(source[0], 'r').read()
155 else:
156 newinput = getPasteBuffer()
157
158 try:
159 if statement.inputFrom:
160 newinput = open(statement.inputFrom, 'r').read()
161 else:
162 newinput = getPasteBuffer()
163 except (OSError,), e:
164 print e
165 return 0
166 start, end = self.redirectInPattern.scanString(statement.fullStatement).next()[1:]
167 return self.onecmd('%s%s%s' % (statement.fullStatement[:start],
168 newinput, statement.fullStatement[end:]))
169
151 class Cmd(cmd.Cmd): 170 class Cmd(cmd.Cmd):
152 echo = False 171 echo = False
153 caseInsensitive = True 172 caseInsensitive = True
154 continuationPrompt = '> ' 173 continuationPrompt = '> '
155 shortcuts = {'?': 'help', '!': 'shell', '@': 'load' } 174 shortcuts = {'?': 'help', '!': 'shell', '@': 'load' }
328 - args: command /* with comment complete */ is done 347 - args: command /* with comment complete */ is done
329 - multilineCommand: multiline 348 - multilineCommand: multiline
330 - terminator: ; 349 - terminator: ;
331 - suffix: 350 - suffix:
332 - terminator: ; 351 - terminator: ;
352 >>> print c.parsed('hello <').dump()
333 ''' 353 '''
334 outputParser = pyparsing.oneOf(['>>','>'])('output') 354 outputParser = pyparsing.oneOf(['>>','>'])('output')
335 terminatorParser = pyparsing.oneOf(self.terminators)('terminator') 355 terminatorParser = pyparsing.oneOf(self.terminators)('terminator')
336 stringEnd = pyparsing.stringEnd ^ '\nEOF' 356 stringEnd = pyparsing.stringEnd ^ '\nEOF'
337 multilineCommand = pyparsing.Or([pyparsing.Keyword(c, caseless=self.caseInsensitive) for c in self.multilineCommands])('multilineCommand') 357 multilineCommand = pyparsing.Or([pyparsing.Keyword(c, caseless=self.caseInsensitive) for c in self.multilineCommands])('multilineCommand')
338 oneLineCommand = pyparsing.Word(pyparsing.printables)('command') 358 oneLineCommand = pyparsing.Word(pyparsing.printables)('command')
339 afterElements = \ 359 afterElements = \
340 pyparsing.Optional('|' + pyparsing.SkipTo(outputParser ^ stringEnd)('pipeDest')) + \ 360 pyparsing.Optional('|' + pyparsing.SkipTo(outputParser ^ stringEnd)('pipeTo')) + \
341 pyparsing.Optional(outputParser + pyparsing.SkipTo(stringEnd)('outputDest')) 361 pyparsing.Optional(outputParser + pyparsing.SkipTo(stringEnd)('outputTo'))
342 if self.caseInsensitive: 362 if self.caseInsensitive:
343 multilineCommand.setParseAction(lambda x: x[0].lower()) 363 multilineCommand.setParseAction(lambda x: x[0].lower())
344 oneLineCommand.setParseAction(lambda x: x[0].lower()) 364 oneLineCommand.setParseAction(lambda x: x[0].lower())
345 self.parser = ( 365 self.parser = (
346 (((multilineCommand ^ oneLineCommand) + pyparsing.SkipTo(terminatorParser)('args') + terminatorParser)('statement') + 366 (((multilineCommand ^ oneLineCommand) + pyparsing.SkipTo(terminatorParser)('args') + terminatorParser)('statement') +
352 afterElements) 372 afterElements)
353 ) 373 )
354 self.commentGrammars.ignore(pyparsing.sglQuotedString).ignore(pyparsing.dblQuotedString).setParseAction(lambda x: '') 374 self.commentGrammars.ignore(pyparsing.sglQuotedString).ignore(pyparsing.dblQuotedString).setParseAction(lambda x: '')
355 self.commentInProgress.ignore(pyparsing.sglQuotedString).ignore(pyparsing.dblQuotedString).ignore(pyparsing.cStyleComment) 375 self.commentInProgress.ignore(pyparsing.sglQuotedString).ignore(pyparsing.dblQuotedString).ignore(pyparsing.cStyleComment)
356 self.parser.ignore(pyparsing.sglQuotedString).ignore(pyparsing.dblQuotedString).ignore(self.commentGrammars).ignore(self.commentInProgress) 376 self.parser.ignore(pyparsing.sglQuotedString).ignore(pyparsing.dblQuotedString).ignore(self.commentGrammars).ignore(self.commentInProgress)
377
378 inputMark = pyparsing.Literal('<')
379 inputMark.setParseAction(lambda x: '')
380 inputFrom = pyparsing.Word(pyparsing.printables)('inputFrom')
381 inputFrom.setParseAction(lambda x: (x and open(x[0]).read()) or getPasteBuffer())
382 self.inputParser = inputMark + pyparsing.Optional(inputFrom)
383 self.inputParser.ignore(pyparsing.sglQuotedString).ignore(pyparsing.dblQuotedString).ignore(self.commentGrammars).ignore(self.commentInProgress)
357 384
358 def parsed(self, s): 385 def parsed(self, raw):
386 s = self.inputParser.transformString(raw)
387 for (shortcut, expansion) in self.shortcuts.items():
388 if s.startswith(shortcut):
389 s = s.replace(shortcut, expansion + ' ', 1)
390 break
359 result = self.parser.parseString(s) 391 result = self.parser.parseString(s)
360 result['command'] = result.multilineCommand or result.command 392 result['command'] = result.multilineCommand or result.command
393 result['statement'] = ' '.join(result.statement)
394 result['raw'] = raw
395 result['clean'] = self.commentGrammars.transformString(result.statement)
361 result['cleanArgs'] = self.commentGrammars.transformString(result.args) 396 result['cleanArgs'] = self.commentGrammars.transformString(result.args)
362 result['statement'] = ' '.join(result.statement)
363 return result 397 return result
364 398
365 def extractCommand(self, statement): 399 def extractCommand(self, statement):
366 try: 400 try:
367 (command, args) = statement.split(None,1) 401 (command, args) = statement.split(None,1)
384 line = line.strip() 418 line = line.strip()
385 if not line: 419 if not line:
386 return 420 return
387 if not pyparsing.Or(self.commentGrammars).setParseAction(lambda x: '').transformString(line): 421 if not pyparsing.Or(self.commentGrammars).setParseAction(lambda x: '').transformString(line):
388 return 422 return
389 statement = self.parsed(line) 423 try:
390 while (statement.command in self.multilineCommands) and not \ 424 statement = self.parsed(line)
391 (statement.terminator or assumeComplete): 425 while statement.multilineCommand and not (statement.terminator or assumeComplete):
392 statement = self.parsed('%s\n%s' % (statement.fullStatement, 426 statement = self.parsed('%s\n%s' % (statement.raw,
393 self.pseudo_raw_input(self.continuationPrompt))) 427 self.pseudo_raw_input(self.continuationPrompt)))
428 except Exception, e:
429 print e
430 return 0
394 431
395 statekeeper = None 432 statekeeper = None
396 stop = 0 433 stop = 0
397 if statement.input: 434
398 try: 435 if statement.pipeTo:
399 if statement.inputFrom:
400 newinput = open(statement.inputFrom, 'r').read()
401 else:
402 newinput = getPasteBuffer()
403 except (OSError,), e:
404 print e
405 return 0
406 start, end = self.redirectInPattern.scanString(statement.fullStatement).next()[1:]
407 return self.onecmd('%s%s%s' % (statement.fullStatement[:start],
408 newinput, statement.fullStatement[end:]))
409 if statement.pipe and statement.pipeTo:
410 redirect = subprocess.Popen(statement.pipeTo, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) 436 redirect = subprocess.Popen(statement.pipeTo, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
411 statekeeper = Statekeeper(self, ('stdout',)) 437 statekeeper = Statekeeper(self, ('stdout',))
412 self.stdout = redirect.stdin 438 self.stdout = redirect.stdin
413 elif statement.output: 439 elif statement.output:
414 statekeeper = Statekeeper(self, ('stdout',)) 440 statekeeper = Statekeeper(self, ('stdout',))
425 statekeeper = Statekeeper(self, ('stdout',)) 451 statekeeper = Statekeeper(self, ('stdout',))
426 self.stdout = tempfile.TemporaryFile() 452 self.stdout = tempfile.TemporaryFile()
427 if statement.output == '>>': 453 if statement.output == '>>':
428 self.stdout.write(getPasteBuffer()) 454 self.stdout.write(getPasteBuffer())
429 try: 455 try:
430 stop = cmd.Cmd.onecmd(self, statement.statement) 456 stop = cmd.Cmd.onecmd(self, statement.clean)
431 except Exception, e: 457 except Exception, e:
432 print e 458 print e
433 try: 459 try:
434 if statement.command not in self.excludeFromHistory: 460 if statement.command not in self.excludeFromHistory:
435 self.history.append(statement.fullStatement) 461 self.history.append(statement.raw)
436 finally: 462 finally:
437 if statekeeper: 463 if statekeeper:
438 if statement.output and not statement.outputTo: 464 if statement.output and not statement.outputTo:
439 self.stdout.seek(0) 465 self.stdout.seek(0)
440 try: 466 try: