在pyparsing中引发自定义异常

时间:2012-11-15 07:57:15

标签: python pyparsing

我已将这些定义为pyparsing

中语法的一部分
argument = oneOf(valid_arguments)
function_name = oneOf(valid_functions)
function_call = Group(function_name + LPAR + argument + RPAR)

其中valid_argumentvalid_function是分别包含有效参数名称和函数名称的字符串列表。

现在我想生成自定义异常,以防列名不是valid_arguments的一部分,而function_name不是函数名之一。我怎么能用pyparsing做到这一点?

示例:

arguments = ["abc", "bcd", "efg"]
function_names = ['avg', 'min', 'max']

如果我解析avg(xyz),我应该提出InvalidArgumentError,如果我解析sum(abc),我想提出InvalidFunctionError我在两个模块中定义的{{1}}叫exception.py

1 个答案:

答案 0 :(得分:4)

您可以在解析操作中引发任何类型的异常,但要将异常报告一直返回到您的调用代码,请将您的异常类派生自ParseFatalException。以下是您请求的特殊异常类型的示例。

from pyparsing import *

class InvalidArgumentException(ParseFatalException):
    def __init__(self, s, loc, msg):
        super(InvalidArgumentException, self).__init__(
                s, loc, "invalid argument '%s'" % msg)

class InvalidFunctionException(ParseFatalException): 
    def __init__(self, s, loc, msg):
        super(InvalidFunctionException, self).__init__(
                s, loc, "invalid function '%s'" % msg)

def error(exceptionClass):
    def raise_exception(s,l,t):
        raise exceptionClass(s,l,t[0])
    return Word(alphas,alphanums).setParseAction(raise_exception)

LPAR,RPAR = map(Suppress, "()")
valid_arguments = ['abc', 'bcd', 'efg']
valid_functions = ['avg', 'min', 'max']
argument = oneOf(valid_arguments) | error(InvalidArgumentException)
function_name = oneOf(valid_functions)  | error(InvalidFunctionException)
# add some results names to make it easier to get at the parsed data
function_call = Group(function_name('fname') + LPAR + argument('arg') + RPAR)

tests = """\
    avg(abc)
    sum(abc)
    avg(xyz)
    """.splitlines()
for test in tests:
    if not test.strip(): continue
    try:
        print test.strip()
        result = function_call.parseString(test)
    except ParseBaseException as pe:
        print pe
    else:
        print result[0].dump()
    print

打印:

avg(abc)
['avg', 'abc']
- arg: abc
- fname: avg

sum(abc)
invalid function 'sum' (at char 4), (line:1, col:5)

avg(xyz)
invalid argument 'xyz' (at char 8), (line:1, col:9)