在 pyparsing 中引发自定义异常

2023-12-26

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

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

where valid_argument and valid_function是分别包含有效参数名称和函数名称的字符串列表。

现在,如果列名不是 valid_arguments 的一部分并且 function_name 不是函数名称之一,我想生成自定义异常。我怎样才能用 pyparsing 做到这一点?

Example:

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

如果我解析avg(xyz),我应该想提高InvalidArgumentError如果我解析sum(abc)我想提高InvalidFunctionError我在一个名为 exceptes.py 的单独模块中定义了这两个内容


您可以在解析操作中引发任何类型的异常,但要让异常一直报告回调用代码,请让您的异常类派生自 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

prints:

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 pyparsing 中引发自定义异常 的相关文章

随机推荐