其他分享
首页 > 其他分享> > 引发pyparsing中的自定义异常

引发pyparsing中的自定义异常

作者:互联网

我已经将这些定义为pyparsing语法的一部分

argument = oneOf(valid_arguments)
function_name = oneOf(valid_functions)
function_call = Group(function_name + LPAR + argument + RPAR)

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

现在,我想生成自定义异常,以防万一列名不是valid_arguments的一部分并且function_name不是函数名之一.如何使用pyparsing做到这一点?

例:

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

如果我解析avg(xyz),我应该要引发InvalidArgumentError;如果我解析sum(abc),我要引发InvalidFunctionError,我都在一个单独的模块中定义了InvalidFunctionError.

解决方法:

您可以在解析动作中引发任何类型的异常,但是要获取该异常以将其报告一直返回到调用代码,请使异常类派生自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)

标签:pyparsing,python
来源: https://codeday.me/bug/20191031/1977301.html