Mercurial > python-cmd2
view lineend.py @ 65:4e028e9ec4c2
punctFinder going to go in
author | catherine@Elli.myhome.westell.com |
---|---|
date | Mon, 23 Jun 2008 12:51:37 -0400 |
parents | a0f7702f2a4b |
children |
line wrap: on
line source
import pyparsing, sys, doctest integer_pattern = pyparsing.Optional(pyparsing.Word(pyparsing.nums)) terminators = [pyparsing.Literal(';') + integer_pattern, pyparsing.Literal('\\t') + integer_pattern] complete_pattern = reduce(lambda x, y: x ^ y, terminators) redirect_pattern = pyparsing.oneOf('< >') + pyparsing.restOfLine pipe_pattern = pyparsing.Literal('|') + pyparsing.restOfLine for pattern in (complete_pattern, redirect_pattern, pipe_pattern): pattern.ignore(pyparsing.sglQuotedString) pattern.ignore(pyparsing.dblQuotedString) def parse(txt): """ >>> sorted(parse('select * from dual;').items()) [('inputFrom', None), ('outputTo', None), ('pipeTo', None), ('terminator', [';'])] >>> sorted(parse('select * from dual E').items()) [('inputFrom', None), ('outputTo', None), ('pipeTo', None), ('terminator', None)] >>> sorted(parse('select * from').items()) [('inputFrom', None), ('outputTo', None), ('pipeTo', None), ('terminator', None)] >>> sorted(parse('select * from dual; > result.txt').items()) [('inputFrom', None), ('outputTo', 'result.txt'), ('pipeTo', None), ('terminator', [';'])] >>> sorted(parse("select * from dual where val = 'x > y'").items()) [('inputFrom', None), ('outputTo', None), ('pipeTo', None), ('terminator', None)] >>> sorted(parse('select * from dual; | wc -c').items()) [('inputFrom', None), ('outputTo', None), ('pipeTo', 'wc -c'), ('terminator', [';'])] >>> sorted(parse('select * from dual; | sort > sorted.txt').items()) [('inputFrom', None), ('outputTo', None), ('pipeTo', 'sort > sorted.txt'), ('terminator', [';'])] """ result = {'inputFrom': None, 'outputTo': None, 'pipeTo': None, 'terminator': None} found = complete_pattern.searchString(txt) if found: result['terminator'] = found[0][:] found = pipe_pattern.searchString(txt) if found: result['pipeTo'] = found[0][1].strip() else: # pipe overrides redirects found = redirect_pattern.searchString(txt) if found: if found[0][0] == '>': result['outputTo'] = found[0][1].strip() else: result['inputFrom'] = found[0][1].strip() return result if __name__ == '__main__': doctest.testmod()