使用行连续pyparsing命令行字符串

时间:2013-05-01 15:43:29

标签: python pyparsing

我正在尝试使用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']]

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

1 个答案:

答案 0 :(得分:4)

使用上面发布的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