小编Kei*_*ald的帖子

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)
Run Code Online (Sandbox Code Playgroud)

结果是:

['shellcmd', ['-arg1', 'val1'], ['-arg2', 'val2'], ['-arg3', 'val3'], ['-arg4', "'quoted"]]
Run Code Online (Sandbox Code Playgroud)

当我想要的是这样的时候:

['shellcmd', ['-arg1', 'val1'], ['-arg2', 'val2'], ['-arg3', 'val3'], ['-arg4', 'quoted line-continued …
Run Code Online (Sandbox Code Playgroud)

python pyparsing

4
推荐指数
1
解决办法
462
查看次数

标签 统计

pyparsing ×1

python ×1