Python pyparsing.ParseException() Examples

The following are 30 code examples of pyparsing.ParseException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyparsing , or try the search function .
Example #1
Source File: expression.py    From monasca-analytics with Apache License 2.0 6 votes vote down vote up
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)) 
Example #2
Source File: test_bibparse.py    From phpsploit with GNU General Public License v3.0 6 votes vote down vote up
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') 
Example #3
Source File: test_bibparse.py    From phpsploit with GNU General Public License v3.0 6 votes vote down vote up
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') 
Example #4
Source File: xchatscrollback.py    From plaso with Apache License 2.0 6 votes vote down vote up
def VerifyStructure(self, parser_mediator, line):
    """Verify that this file is a XChat scrollback log file.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      line (str): line from a text file.

    Returns:
      bool: True if the line was successfully parsed.
    """
    try:
      structure = self.LOG_LINE.parseString(line)
    except pyparsing.ParseException:
      logger.debug('Not a XChat scrollback log file')
      return False

    timestamp = self._GetValueFromStructure(structure, 'timestamp')
    try:
      int(timestamp, 10)
    except (TypeError, ValueError):
      logger.debug('Not a XChat scrollback log file, invalid timestamp.')
      return False

    return True 
Example #5
Source File: __init__.py    From OpenMTC with Eclipse Public License 1.0 6 votes vote down vote up
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") 
Example #6
Source File: apt_history.py    From plaso with Apache License 2.0 6 votes vote down vote up
def VerifyStructure(self, parser_mediator, line):
    """Verify that this file is an APT History log file.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      line (str): single line from the text file.

    Returns:
      bool: True if this is the correct parser, False otherwise.
    """
    try:
      self._RECORD_START.parseString(line)
      # Reset stored values for parsing a new file.
      self._ResetState()
    except pyparsing.ParseException as exception:
      logger.debug('Not an APT History log file: {0!s}'.format(exception))
      return False

    return True 
Example #7
Source File: stp_global.py    From ccat with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #8
Source File: selinux.py    From plaso with Apache License 2.0 6 votes vote down vote up
def VerifyStructure(self, parser_mediator, line):
    """Verifies if a line from a text file is in the expected format.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      line (str): line from a text file.

    Returns:
      bool: True if the line is in the expected format, False if not.
    """
    try:
      structure = self._SELINUX_LOG_LINE.parseString(line)
    except pyparsing.ParseException as exception:
      logger.debug(
          'Unable to parse SELinux audit.log file with error: {0!s}'.format(
              exception))
      return False

    return 'type' in structure and 'msg' in structure 
Example #9
Source File: dpkg.py    From plaso with Apache License 2.0 6 votes vote down vote up
def VerifyStructure(self, parser_mediator, line):
    """Verifies if a line from a text file is in the expected format.

    Args:
      parser_mediator (ParserMediator): parser mediator.
      line (str): line from a text file.

    Returns:
      bool: True if the line is in the expected format, False if not.
    """
    try:
      structure = self._DPKG_LOG_LINE.parseString(line)
    except pyparsing.ParseException as exception:
      logger.debug(
          'Unable to parse Debian dpkg.log file with error: {0!s}'.format(
              exception))
      return False

    return 'date_time' in structure and 'body' in structure 
Example #10
Source File: c_parser.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #11
Source File: storm_control.py    From ccat with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #12
Source File: expression_parser.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
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,
            ],
        ) 
Example #13
Source File: setupapi.py    From plaso with Apache License 2.0 6 votes vote down vote up
def VerifyStructure(self, parser_mediator, line):
    """Verify that this file is a Windows Setupapi log file.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      line (str): single line from the text file.

    Returns:
      bool: True if this is the correct parser, False otherwise.
    """
    try:
      self._LOG_HEADER_START.parseString(line)
      # Reset stored values for parsing a new file.
      self._last_end_time = None
      self._last_entry_type = None
    except pyparsing.ParseException as exception:
      logger.debug('Not a Windows Setupapi log file: {0!s}'.format(exception))
      return False

    return True 
Example #14
Source File: parser.py    From linehaul with Apache License 2.0 6 votes vote down vote up
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) 
Example #15
Source File: text_parser.py    From plaso with Apache License 2.0 6 votes vote down vote up
def testConstantIPv4(self):
    """Tests parsing with the IPV4_ADDRESS constant."""
    self.assertTrue(
        text_parser.PyparsingConstants.IPV4_ADDRESS.parseString(
            '123.51.234.52'))
    self.assertTrue(
        text_parser.PyparsingConstants.IPV4_ADDRESS.parseString(
            '255.254.23.1'))
    self.assertTrue(
        text_parser.PyparsingConstants.IPV4_ADDRESS.parseString('1.1.34.2'))

    with self.assertRaises(pyparsing.ParseException):
      text_parser.PyparsingConstants.IPV4_ADDRESS.parseString('a.1.34.258')

    with self.assertRaises(pyparsing.ParseException):
      text_parser.PyparsingConstants.IPV4_ADDRESS.parseString('.34.258')

    with self.assertRaises(pyparsing.ParseException):
      text_parser.PyparsingConstants.IPV4_ADDRESS.parseString('34.258') 
Example #16
Source File: utils.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #17
Source File: parser.py    From asn1tools with MIT License 6 votes vote down vote up
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] 
Example #18
Source File: evaluator.py    From manila with Apache License 2.0 6 votes vote down vote up
def evaluate(expression, **kwargs):
    """Evaluates an expression.

    Provides the facility to evaluate mathematical expressions, and to
    substitute variables from dictionaries into those expressions.

    Supports both integer and floating point values, and automatic
    promotion where necessary.
    """
    global _parser
    if _parser is None:
        _parser = _def_parser()

    global _vars
    _vars = kwargs

    try:
        result = _parser.parseString(expression, parseAll=True)[0]
    except pyparsing.ParseException as e:
        msg = _("ParseException: %s") % six.text_type(e)
        raise exception.EvaluatorParseException(reason=msg)

    return result.eval() 
Example #19
Source File: test_parser.py    From pyjsgf with MIT License 6 votes vote down vote up
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) 
Example #20
Source File: text_parser.py    From plaso with Apache License 2.0 6 votes vote down vote up
def testConstants(self):
    """Tests parsing with constants."""
    with self.assertRaises(pyparsing.ParseException):
      text_parser.PyparsingConstants.MONTH.parseString('MMo')
    with self.assertRaises(pyparsing.ParseException):
      text_parser.PyparsingConstants.MONTH.parseString('M')
    with self.assertRaises(pyparsing.ParseException):
      text_parser.PyparsingConstants.MONTH.parseString('March', parseAll=True)

    self.assertTrue(text_parser.PyparsingConstants.MONTH.parseString('Jan'))

    line = '# This is a comment.'
    parsed_line = text_parser.PyparsingConstants.COMMENT_LINE_HASH.parseString(
        line)
    self.assertEqual(parsed_line[-1], 'This is a comment.')
    self.assertEqual(len(parsed_line), 2) 
Example #21
Source File: influxdb.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
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 
Example #22
Source File: requirements.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #23
Source File: pass_manager.py    From monasca-analytics with Apache License 2.0 6 votes vote down vote up
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 
Example #24
Source File: _qdisc.py    From tcconfig with MIT License 5 votes vote down vote up
def __parse_bandwidth_rate(self, line):
        parse_param_name = "rate"
        pattern = pp.SkipTo(parse_param_name, include=True) + pp.Word(pp.alphanums + "." + ":")

        try:
            result = pattern.parseString(line)[-1]
            if typepy.is_not_null_string(result):
                result = result.rstrip("bit")
                self.__parsed_param[parse_param_name] = result
        except pp.ParseException:
            pass 
Example #25
Source File: _qdisc.py    From tcconfig with MIT License 5 votes vote down vote up
def __parse_netem_delay_distro(self, line):
        parse_param_name = "delay"
        pattern = (
            pp.SkipTo(parse_param_name, include=True)
            + pp.Word(pp.nums + ".msu")
            + pp.Word(pp.nums + ".msu")
        )

        try:
            parsed_list = pattern.parseString(line)
            self.__parsed_param[parse_param_name] = parsed_list[2]
            self.__parsed_param["delay-distro"] = parsed_list[3]
        except pp.ParseException:
            pass 
Example #26
Source File: sophos_av.py    From plaso with Apache License 2.0 5 votes vote down vote up
def VerifyStructure(self, parser_mediator, line):
    """Verify that this file is a Sophos Anti-Virus log file.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfVFS.
      line (str): line from a text file.

    Returns:
      bool: True if the line is in the expected format, False if not.
    """
    try:
      structure = self._LOG_LINE.parseString(line)
    except pyparsing.ParseException:
      logger.debug('Not a Sophos Anti-Virus log file')
      return False

    # Expect spaces at position 9 and 16.
    if ' ' not in (line[8], line[15]):
      logger.debug('Not a Sophos Anti-Virus log file')
      return False

    time_elements_tuple = self._GetValueFromStructure(structure, 'date_time')
    try:
      dfdatetime_time_elements.TimeElements(
          time_elements_tuple=time_elements_tuple)
    except ValueError:
      logger.debug((
          'Not a Sophos Anti-Virus log file, invalid date and time: '
          '{0!s}').format(time_elements_tuple))
      return False

    return True 
Example #27
Source File: test_config.py    From monasca-analytics with Apache License 2.0 5 votes vote down vote up
def get_exception_from_str(string):
    if string == p.ParseSyntaxException.__name__:
        return p.ParseSyntaxException
    if string == p.ParseFatalException.__name__:
        return p.ParseFatalException
    if string == p.ParseException.__name__:
        return p.ParseException
    raise Exception("Invalid exception name: '{}'".format(string)) 
Example #28
Source File: markers.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, marker):
        try:
            self._markers = _coerce_parse_result(MARKER.parseString(marker))
        except ParseException as e:
            err_str = "Invalid marker: {0!r}, parse error at {1!r}".format(
                marker, marker[e.loc:e.loc + 8])
            raise InvalidMarker(err_str) 
Example #29
Source File: mac_securityd.py    From plaso with Apache License 2.0 5 votes vote down vote up
def VerifyStructure(self, parser_mediator, line):
    """Verify that this file is a securityd log file.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      line (str): line from a text file.

    Returns:
      bool: True if the line is in the expected format, False if not.
    """
    self._last_month = 0
    self._year_use = parser_mediator.GetEstimatedYear()

    try:
      structure = self.SECURITYD_LINE.parseString(line)
    except pyparsing.ParseException:
      logger.debug('Not a MacOS securityd log file')
      return False

    time_elements_tuple = self._GetTimeElementsTuple(structure)

    try:
      dfdatetime_time_elements.TimeElements(
          time_elements_tuple=time_elements_tuple)
    except ValueError:
      logger.debug(
          'Not a MacOS securityd log file, invalid date and time: {0!s}'.format(
              time_elements_tuple))
      return False

    self._last_month = time_elements_tuple[1]

    return True 
Example #30
Source File: xchatlog.py    From plaso with Apache License 2.0 5 votes vote down vote up
def VerifyStructure(self, parser_mediator, line):
    """Verify that this file is a XChat log file.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      line (str): line from a text file.

    Returns:
      bool: True if the line is in the expected format, False if not.
    """
    try:
      structure = self._HEADER.parseString(line)
    except pyparsing.ParseException:
      logger.debug('Not a XChat log file')
      return False

    time_elements_tuple = self._GetValueFromStructure(structure, 'date_time')
    try:
      _, month, day, hours, minutes, seconds, year = time_elements_tuple
    except TypeError:
      logger.debug('Not a XChat log file, invalid date and time: {0!s}'.format(
          time_elements_tuple))
      return False

    month = timelib.MONTH_DICT.get(month.lower(), 0)

    time_elements_tuple = (year, month, day, hours, minutes, seconds)

    try:
      dfdatetime_time_elements.TimeElements(
          time_elements_tuple=time_elements_tuple)
    except ValueError:
      logger.debug('Not a XChat log file, invalid date and time: {0!s}'.format(
          time_elements_tuple))
      return False

    return True