Skip to content Skip to sidebar Skip to footer

Pyparsing: Get Token Location In Results Name

I am working on a program that parses a command line with pyparsing. It uses the readline library to provide command edition and completion. In the context of the application, a va

Solution 1:

Try adding a locator to your command and path expressions:

locator = Empty().setParseAction(lambda s,l,t: l)
deflocatedExpr(expr):
    return Group(locator("location") + expr("value"))

classShell(object):
    def__init__(self):
        # Simplified grammar of the command line# path command parameters#command = Word(alphanums + '_').setResultsName('command')
        command = locatedExpr(Word(alphanums + '_'))('command')
        bookmark = Regex('@([A-Za-z0-9:_.]|-)+')
        pathstd = Regex('([A-Za-z0-9:_.]|-)*' + '/' + '([A-Za-z0-9:_./]|-)*') \
                | '..' | '.'#path = (bookmark | pathstd | '*')('path')
        path = locatedExpr(bookmark | pathstd | '*')('path')
        parser = Optional(path) + Optional(command) # + Optional(parameters)
        self.parser = parser

Now you should be able to access path.location and path.value to get the location and matched text for the path, and likewise for command.

Post a Comment for "Pyparsing: Get Token Location In Results Name"