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