我正在开发一个用pyparsing解析命令行的程序。它使用readline库来提供命令编辑和完成。
在应用程序的上下文中,有效的命令行是路径(可选),后跟命令名称(可选)和一些参数< / em>(也是可选的)。
为了提供命令完成,应用程序解析命令行以查看要完成的元素是路径,命令还是完成。 Readline给出了需要完成的元素的索引。我想将这些索引与路径的位置,命令名称或pyparsing返回的已解析结果的参数进行匹配。
如何获取不同令牌的位置并继续使用setResultsName()来命名我的令牌?
from pyparsing import Optional, Regex, Word
from pyparsing import alphanums
class Shell(object):
def __init__(self):
# Simplified grammar of the command line
# path command parameters
command = Word(alphanums + '_').setResultsName('command')
bookmark = Regex('@([A-Za-z0-9:_.]|-)+')
pathstd = Regex('([A-Za-z0-9:_.]|-)*' + '/' + '([A-Za-z0-9:_./]|-)*') \
| '..' | '.'
path = (bookmark | pathstd | '*')('path')
parser = Optional(path) + Optional(command) # + Optional(parameters)
self.parser = parser
def parse_cmdline(self, line):
parse_results = self.parser.parseString(line)
path = parse_results.path
command = parse_results.command
return (parse_results, path, command)
def complete(self):
"""Completion method called by readline"""
cmdline = readline.get_line_buffer()
(result_trees, path, command) = self.parse_cmdline(cmdline)
beg = readline.get_begidx()
end = readline.get_endidx()
prefix = cmdline[beg:end]
# if beg == path.location:
# completion = self.get_path_completion()
# elif beg == command.location:
# completion = self.get_command_completion()
# elif beg in parameters.location:
# completion = self.get_parameter_completion()
答案 0 :(得分:3)
尝试在命令和路径表达式中添加定位器:
locator = Empty().setParseAction(lambda s,l,t: l)
def locatedExpr(expr):
return Group(locator("location") + expr("value"))
class Shell(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
现在,您应该能够访问path.location
和path.value
以获取路径的位置和匹配文本,同样也可以访问命令。