Mercurial > python-cmd2
diff lineend.py @ 60:682588392eaf
experiments with parsing in lineend
author | catherine@Elli.myhome.westell.com |
---|---|
date | Fri, 20 Jun 2008 19:52:39 -0400 |
parents | |
children | 82891de09dbf |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lineend.py Fri Jun 20 19:52:39 2008 -0400 @@ -0,0 +1,41 @@ +import pyparsing, sys, doctest + +pattern = pyparsing.Optional(pyparsing.CharsNotIn(';')) + ';' +pattern.ignore(pyparsing.sglQuotedString) +pattern.ignore(pyparsing.sglQuotedString) + +redirect_pattern = pyparsing.Optional(pyparsing.CharsNotIn('<>')) + pyparsing.oneOf('< >') + pyparsing.Word(pyparsing.printables) +redirect_pattern.ignore(pyparsing.sglQuotedString) +redirect_pattern.ignore(pyparsing.sglQuotedString) + +def parse(txt, mustBeTerminated=False): + """ + >>> sorted(parse('select * from dual;', True).items()) + [('complete', True), ('inputFrom', None), ('outputTo', None), ('pipeTo', None)] + >>> sorted(parse('select * from', True).items()) + [('complete', False), ('inputFrom', None), ('outputTo', None), ('pipeTo', None)] + >>> sorted(parse('select * from dual; > result.txt', True).items()) + [('complete', True), ('inputFrom', None), ('outputTo', 'result.txt'), ('pipeTo', None)] + """ + result = {'complete': not mustBeTerminated, 'inputFrom': None, 'outputTo': None, 'pipeTo': None} + if mustBeTerminated: + try: + pattern.parseString(txt) + result['complete'] = True + except pyparsing.ParseException: + pass + + if result['complete']: + try: + parsed = redirect_pattern.parseString(txt) + if parsed[1] == '>': + result['outputTo'] = parsed[2] + else: + result['inputFrom'] = parsed[2] + except pyparsing.ParseException: + pass + return result + +if __name__ == '__main__': + doctest.testmod() + \ No newline at end of file