为什么pyparsing截断解析而不是引发异常

2024-06-25 23:32:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在解决一个问题,该问题围绕使用文本字符串指定有线协议格式展开。基本的想法是,你只把二进制放在电线上,因为这是一个低带宽的环境。但为了做到这一点,双方必须提前就什么意思达成一致,以便能够正确地从电线中提取数值。你知道吗

为了协调“what means what”配置文件的使用。它的核心是每个包体都有定义。以下是一些示例:

你知道吗abc:16分
abc:15分:p
abc:15分:p;定义:14:椭圆曲线

您可以指定一个三个或四个字母的标识符,后跟一个颜色,然后指定位数(通常是四的倍数,但这不能保证),还可以选择另一个冒号,后跟一个“p”表示有一个位用于奇偶校验,或者“ecc”表示有两个位用于ecc。你知道吗

所以把它翻译成pyparsing这就是我得到的:

from pyparsing import *

abbr = Word(alphas)
internal_separator = Literal(":")
bits = Word(nums, min=1, max=2)
parity = Or([CaselessLiteral("P"), CaselessLiteral("ECC")])
separator = Literal(";")

parity_part = internal_separator + parity
statement = Group(abbr + internal_separator + bits + Optional(parity_part))

#statement_list = delimitedList(statement, delim=";")
statement_list = statement + ZeroOrMore(separator + statement)

tests = ( 
    "abc:16",
    "abc:15:p", 
    "abc:15:p; def:14:ecc",
    "abc:17:p; def:q; ghi:21:", #this one should fail!
)

for t in tests:
    try:
        print t, "->", statement_list.parseString(t)
    except Exception as e:
        print e

当我运行这个时,我得到的是:

abc:16 -> [['abc', ':', '16']]
abc:15:p -> [['abc', ':', '15', ':', 'P']]
abc:15:p; def:14:ecc -> [['abc', ':', '15', ':', 'P'], ';', ['def', ':', '14', ':', 'ECC']]
abc:17:p; def:q; ghi:21: -> [['abc', ':', '17', ':', 'P']]

我不明白的是为什么pyparsing只是在上一次测试中截断输出。在我看来,它应该失败,因为它是无效的。我还尝试了delimitedList,得到了相同的行为。你知道吗

我还尝试了最小值为3,最大值为4的“abbr”,这样它就可以确定“:q”是无效的,但这并没有改变任何东西。你知道吗

似乎这个错误不知怎么被吞没了,我不知道为什么,也不知道如何让错误传播开来,以便我能抓住它。你知道吗

我发现这个问题(Trouble doing simple parse in pyparsing)似乎很相关,但也没有给出我想要的答案。你知道吗


Tags: 定义defpyparsingwhatlistwordstatementinternal