当前位置: 首页>>代码示例>>Python>>正文


Python pyparsing.ParseException方法代码示例

本文整理汇总了Python中pyparsing.ParseException方法的典型用法代码示例。如果您正苦于以下问题:Python pyparsing.ParseException方法的具体用法?Python pyparsing.ParseException怎么用?Python pyparsing.ParseException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyparsing的用法示例。


在下文中一共展示了pyparsing.ParseException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: post_query

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def post_query(self, q=None):
        if q is not None:
            try:
                query = query_parser.parseString(q)
            except pyparsing.ParseException:
                api.abort(501, {"cause": "Not implemented error",
                                "detail": "q",
                                "reason": "Query not implemented"})
            resource_type = query[0]
            api.enforce("create resource type", {"name": resource_type})
            schema = pecan.request.indexer.get_resource_type_schema()
            rt = schema.resource_type_from_dict(resource_type, {}, 'creating')
            try:
                pecan.request.indexer.create_resource_type(rt)
            except indexer.ResourceTypeAlreadyExists:
                pass
            pecan.response.status = 204 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:19,代码来源:influxdb.py

示例2: test_invalid_alternative_weights

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def test_invalid_alternative_weights(self):
        # Test that errors are raised if weights aren't used correctly in an
        # alt. set.
        self.assertRaises(TypeError, parse_expansion_string, "/-1/ a | /5/ b")
        self.assertRaises(ParseException, parse_expansion_string, "// a | /5/ b")
        self.assertRaises(ParseException, parse_expansion_string,
                          "/1/ a | /2/ b | // c")
        invalid_uses = [
            "[/2/ a] | /6/ b",
            "/2/ a | [/6/ b]",
            "(/2/ a) | /6/ b",
            "/2/ a | /6/ b | (/12/ c)",
            "/2/ a | (/6/ b)",
            "/2/ test",
        ]
        for s in invalid_uses:
            self.assertRaises(GrammarError, parse_expansion_string, s) 
开发者ID:Danesprite,项目名称:pyjsgf,代码行数:19,代码来源:test_parser.py

示例3: parse_string

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def parse_string(string):
    """Parse given ASN.1 specification string and return a dictionary of
    its contents.

    The dictionary can later be compiled with
    :func:`~asn1tools.compile_dict()`.

    >>> with open('foo.asn') as fin:
    ...     foo = asn1tools.parse_string(fin.read())

    """

    grammar = create_grammar()

    try:
        string = ignore_comments(string)
        tokens = grammar.parseString(string).asList()
    except (ParseException, ParseSyntaxException) as e:
        raise ParseError("Invalid ASN.1 syntax at line {}, column {}: '{}': {}.".format(
            e.lineno,
            e.column,
            e.markInputline(),
            e.msg))

    return tokens[0] 
开发者ID:eerimoq,项目名称:asn1tools,代码行数:27,代码来源:parser.py

示例4: parse_and_validate_formula

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def parse_and_validate_formula(formula, course, activity, numeric_activities):
    """
    Handy function to parse the formula and validate if the activity references
    in the formula are in the numeric_activities list
    Return the parsed formula if no exception raised

    May raise exception: ParseException, ValidateError
    """
    for a in numeric_activities:
        if not isinstance(a, NumericActivity):
            raise TypeError('NumericActivity list is required')
    try:
        parsed_expr = parse(formula, course, activity)
        activities_dict = activities_dictionary(numeric_activities)
        cols = set([])
        cols = cols_used(parsed_expr)
        for col in cols:
            if not col in activities_dict:
                raise ValidationError('Invalid activity reference')
    except ParseException:
        raise ValidationError('Incorrect formula syntax')
    return parsed_expr 
开发者ID:sfu-fas,项目名称:coursys,代码行数:24,代码来源:utils.py

示例5: parse

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def parse(message):
    try:
        parsed = SYSLOG_MESSAGE.parseString(message, parseAll=True)
    except ParseException as exc:
        raise UnparseableSyslogMessage(str(exc)) from None

    data = {}
    data["facility"] = int(parsed.priority / 8)
    data["severity"] = parsed.priority - (data["facility"] * 8)
    data["timestamp"] = parsed.timestamp
    data["hostname"] = _value_or_none(parsed.hostname)
    data["appname"] = parsed.appname
    data["procid"] = parsed.procid
    data["message"] = parsed.message

    return SyslogMessage(**data) 
开发者ID:pypa,项目名称:linehaul,代码行数:18,代码来源:parser.py

示例6: XXXX_create_cast_expression

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def XXXX_create_cast_expression(self, tok):
        if tok.typeof_arg:
            type_expression = self.type_manager.get_type_of(
                tok.typeof_arg.first)
        else:
            type_expression = tok.simple_type

        # Check that casting makes sense.
        target = self.type_manager.get_type_of(type_expression)
        if not target:
            raise pyparsing.ParseException(
                "%s is not a type" % target)

        return c_ast.CFunctionCall(
            function_name='()',
            arguments=[
                c_ast.CLiteral(target),
                tok.expression,
            ],
        ) 
开发者ID:google,项目名称:rekall,代码行数:22,代码来源:expression_parser.py

示例7: _make_attribute

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def _make_attribute(self, tok):
        """Compose a c_ast.CAttribute() object for each attribute."""
        result = []
        for attr_specifier in tok:
            expression = []
            if attr_specifier.args:
                # Try to parse the expression if possible.
                try:
                    expression = [self.expression_parser.parse(
                        attr_specifier.args)]
                except pyparsing.ParseException:
                    pass

            result.append(c_ast.CAttribute(
                attr_specifier.name.first,
                *expression))

        return result 
开发者ID:google,项目名称:rekall,代码行数:20,代码来源:c_parser.py

示例8: _check_update_representation

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def _check_update_representation(self):
        super(SemanticDescriptorController, self)._check_update_representation()

        values = self.request.content.get_values(True)
        if all(k in values for k in ("semanticOpExec", "descriptor")):
            # check if both attribute exist at the same time
            raise CSEContentsUnacceptable("bad request: both semanticOpExec and descriptor exist")
        elif "descriptor" in values:
            # verify if the descriptor conform to the RDF syntax or not
            self._check_descriptor_data(self.values["descriptor"])
        elif "semanticOpExec" in values:
            # verify if the semanticOpExec has a correct SPAROL syntax
            g = Graph()
            try:
                g.parse(values["semanticOpExec"])
            except ParseException:
                raise CSEContentsUnacceptable("The semanticOpExec attribute does not conform to "
                                              "the SPARQL query syntax.")
        else:
            raise CSESyntaxError("Please provide an updated descriptor or a semanticOpExec") 
开发者ID:OpenMTC,项目名称:OpenMTC,代码行数:22,代码来源:__init__.py

示例9: test_names

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def test_names():
    # check various types of names
    # All names can contains alphas, but not some special chars
    bad_chars = '"#%\'(),={}'
    for name_type, dig1f in ((bp.macro_def, False),
                             (bp.field_name, False),
                             (bp.entry_type, False),
                             (bp.cite_key, True)):
        if dig1f: # can start with digit
            assert_equal(name_type.parseString('2t')[0], '2t')
        else:
            assert_raises(ParseException, name_type.parseString, '2t')
        # All of the names cannot contain some characters
        for char in bad_chars:
            assert_raises(ParseException, name_type.parseString, char)
        # standard strings all OK
        assert_equal(name_type.parseString('simple_test')[0], 'simple_test')
    # Test macro ref
    mr = bp.macro_ref
    # can't start with digit
    assert_raises(ParseException, mr.parseString, '2t')
    for char in bad_chars:
        assert_raises(ParseException, mr.parseString, char)
    assert_equal(mr.parseString('simple_test')[0].name, 'simple_test') 
开发者ID:nil0x42,项目名称:phpsploit,代码行数:26,代码来源:test_bibparse.py

示例10: test_comments

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def test_comments():
    res = bp.comment.parseString('@Comment{about something}')
    assert_equal(res.asList(), ['comment', '{about something}'])
    assert_equal(
        bp.comment.parseString('@COMMENT{about something').asList(),
        ['comment', '{about something'])
    assert_equal(
        bp.comment.parseString('@comment(about something').asList(),
        ['comment', '(about something'])
    assert_equal(
        bp.comment.parseString('@COMment about something').asList(),
        ['comment', ' about something'])
    assert_raises(ParseException, bp.comment.parseString,
                  '@commentabout something')
    assert_raises(ParseException, bp.comment.parseString,
                  '@comment+about something')
    assert_raises(ParseException, bp.comment.parseString,
                  '@comment"about something') 
开发者ID:nil0x42,项目名称:phpsploit,代码行数:20,代码来源:test_bibparse.py

示例11: _globalParse___stp_attributes

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def _globalParse___stp_attributes(stp, dct):
    parse_portfast = Suppress('portfast ') + restOfLine
    parse_bpdu = Suppress('portfast bpduguard ') + restOfLine
    parse_loop = Suppress('loopguard ') + restOfLine
    try:
        return util.int_dict_parse(parse_bpdu, stp, 'bpduguard', dct)
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_loop, stp, 'loopguard', dct)
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_portfast, stp, 'portfast', dct)
    except ParseException:
        pass
    return 0 
开发者ID:cisco-config-analysis-tool,项目名称:ccat,代码行数:19,代码来源:stp_global.py

示例12: __ifaceAttributes___storm_check

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def __ifaceAttributes___storm_check(storm,dct):

    parse_level  = Word(alphas)        + Suppress('level ')            + restOfLine
    parse_action = Suppress('action ') + Word(alphas)
    parse_type   = Word(alphas)        + Suppress(Optional("include")) + Word(alphas)
    try:
        value = parse_level.parseString(storm).asList()
        if 'level' in dct:
            dct['level'].append(value)
        else:
            dct['level'] = [value]
        return dct
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_action, storm, 'action', dct)
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_type,   storm, 'type',   dct)
    except ParseException:
        pass 
开发者ID:cisco-config-analysis-tool,项目名称:ccat,代码行数:24,代码来源:storm_control.py

示例13: try_compute_type_table

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def try_compute_type_table(banana):
    """
    Compute the type table for the provided banana string
    if possible. Does not throw any exception if it fails.
    :type banana: str
    :param banana: The string to parse and type check.
    """
    try:
        # Convert the grammar into an AST
        parser = grammar.banana_grammar()
        ast = parser.parse(banana)
        # Compute the type table for the given AST
        return typeck.typeck(ast)
    except exception.BananaException:
        return None
    except p.ParseSyntaxException:
        return None
    except p.ParseFatalException:
        return None
    except p.ParseException:
        return None 
开发者ID:openstack,项目名称:monasca-analytics,代码行数:23,代码来源:pass_manager.py

示例14: validate_expression

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def validate_expression(expr_string):
    """
    Validate the provided expression string.
    :type expr_string: str
    :param expr_string: Expression string to validate.
    :returns: Returns a handle that can be use to validate
              name usage against an environment.
    :raises: exception.BananaInvalidExpression
    """
    if not isinstance(expr_string, six.string_types):
        raise exception.BananaArgumentTypeError(
            expected_type=six.string_types[0],
            received_type=type(expr_string)
        )
    parser = ExpressionParser()
    try:
        res = parser.parse_tree(expr_string)
        return ExpressionHandle(res, expr_string)
    except p.ParseException as e:
        raise exception.BananaInvalidExpression(str(e)) 
开发者ID:openstack,项目名称:monasca-analytics,代码行数:22,代码来源:expression.py

示例15: __init__

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import ParseException [as 别名]
def __init__(self, requirement_string):
        try:
            req = REQUIREMENT.parseString(requirement_string)
        except ParseException as e:
            raise InvalidRequirement(
                "Invalid requirement, parse error at \"{0!r}\"".format(
                    requirement_string[e.loc:e.loc + 8]))

        self.name = req.name
        if req.url:
            parsed_url = urlparse.urlparse(req.url)
            if not (parsed_url.scheme and parsed_url.netloc) or (
                    not parsed_url.scheme and not parsed_url.netloc):
                raise InvalidRequirement("Invalid URL given")
            self.url = req.url
        else:
            self.url = None
        self.extras = set(req.extras.asList() if req.extras else [])
        self.specifier = SpecifierSet(req.specifier)
        self.marker = req.marker if req.marker else None 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:22,代码来源:requirements.py


注:本文中的pyparsing.ParseException方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。