我正在尝试使用 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']]
非常感谢您帮助指出我的错误并进行修复。
最佳答案
使用 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
.
关于python - pyparsing命令行字符串与行延续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16321432/