4

我正在尝试使用 pyparsing 解析命令行样式字符串,其中参数本身可能包含反斜杠行继续,例如-arg4以下示例中的值:

import pyparsing as pp

cmd = r"""shellcmd -arg1 val1 -arg2 val2 \
-arg3 val3 \
-arg4 'quoted \
    line-continued \
    string \
'"""

continuation = '\\' + pp.LineEnd()

option = pp.Word('-', pp.alphanums)
arg1 = ~pp.Literal('-') + pp.Word(pp.printables)
arg2 = pp.quotedString
arg2.ignore(continuation)
arg = arg1 | arg2

command = pp.Word(pp.alphas) + pp.ZeroOrMore(pp.Group(option + pp.Optional(arg)))
command.ignore(continuation)

print command.parseString(cmd)

结果是:

['shellcmd', ['-arg1', 'val1'], ['-arg2', 'val2'], ['-arg3', 'val3'], ['-arg4', "'quoted"]]

当我想要的是这样的东西时:

['shellcmd', ['-arg1', 'val1'], ['-arg2', 'val2'], ['-arg3', 'val3'], ['-arg4', 'quoted line-continued string']]

非常感谢您帮助指出我的错误和修复。

4

1 回答 1

6

使用cmd您在上面发布的内容,我会像这样解析它:

from pyparsing import *

continuation = ('\\' + LineEnd()).suppress()
name = Word(alphanums)

# Parse out the multiline quoted string
def QString(s,loc,tokens):
    text = Word(alphanums+'-') + Optional(continuation)
    g    = Combine(ZeroOrMore(text),adjacent=False, joinString=" ")
    return g.parseString(tokens[0])

arg    = name + Optional(continuation)
qarg   = QuotedString("\'",multiline=True)
qarg.setParseAction(QString)

vals   = Group(ZeroOrMore(arg | qarg))
option = Literal("-").suppress() + Group(name + vals)
grammar = name + ZeroOrMore(option)

sol = grammar.parseString(cmd)
print sol

给予:

['shellcmd', ['arg1', ['val1']], ['arg2', ['val2']], ['arg3', ['val3']], ['arg4', ['quoted line-continued string']]]

这里真正的关键是使用可以省去很多麻烦的QuotedString选项。multiline=True此解决方案比您提出的解决方案更灵活,能够处理多个参数,即-arg a b c甚至-arg a b 'long-string-with-dashes' c d e.

于 2013-05-02T14:52:04.297 回答