pyparsing - 同一条语句的第二次执行抛出异常

pyparsing - 2nd execution of the same statement throws an exception

你能解释一下为什么第二次执行完全相同的 parseString 会抛出 pyparsing.ParseException: not a subentry 异常吗?

代码:

from pyparsing import *
from pprint import pprint

indentStack = [1]
stmt = Forward()
suite = indentedBlock(stmt, indentStack)

funcDecl = "def" + Word(printables)
funcDef = Group( funcDecl + suite )

stmt << ( funcDef | "open" | "close")
module_body = OneOrMore(stmt)

code="""\
def process
    open
    close"""

# first execution - works fine, but modifies funcDef
pprint(funcDef)
f1 = funcDef.parseString(code)
pprint(f1)

# second execution
pprint(funcDef)
f2 = funcDef.parseString(code)  ### throws pyparsing.ParseException: not a subentry (at char 16), (line:2, col:5)
pprint(f2)


pyparsing.ParseException: not a subentry (at char 16), (line:2, col:5)

我试图简化 pyparsing wiki 中可用的示例: http://pyparsing.wikispaces.com/file/view/indentedGrammarExample.py

完整堆栈跟踪:https://pastebin.com/QXF5ZJZ7

Link 到 parseString 的文档:https://pythonhosted.org/pyparsing/pyparsing.ParserElement-class.html#parseString

编辑 2018-02-20

我将代码扩展了 pprint(funcDef),我发现在第一次执行 funcDef.parseString(code) funcDef 的定义已更改自:

来自:

Group:({{"def" W:(0123...)} indented block})

至:

Group:({"def" W:(0123...) indented block})

编辑 2018-02-21

在第二次执行 funcDef.parseString(code) 之前添加 indentStack.pop() 解决了问题。

值得一提的是indentStack = [1]并没有解决问题。这是一个非常有趣的案例,所以我创建了两个片段来显示差异(我还在库中添加了一些额外的调试打印):

在这种情况下,堆栈有多层深度。

在第二次执行 funcDef.parseString(code) 之前添加 indentStack[:] = [1] 解决了问题。