4.13. foundations.parsers

parsers.py

Platform:
Windows, Linux, Mac Os X.
Description:
This module defines the SectionsFileParser class, PlistFileParser class and others parsing related objects.
Others:
Portions of the code from Fredrik Lundh: http://effbot.org/zone/element-iterparse.htm

4.13.1. Module Attributes

foundations.parsers.LOGGER

4.13.2. Functions

foundations.parsers.getAttributeCompound(attribute, value=None, splitter='|', bindingIdentifier='@')[source]

This definition returns an attribute compound.

Usage:

>>> data = "@Link | Value | Boolean | Link Parameter"
>>> attributeCompound = foundations.parsers.getAttributeCompound("Attribute Compound", data)
>>> attributeCompound.name
Attribute Compound
>>> attributeCompound.value
Value
>>> attributeCompound.link
@Link
>>> attributeCompound.type
Boolean
>>> attributeCompound.alias
Link Parameter
Parameters:
  • attribute – Attribute. ( String )
  • value – Attribute value. ( Object )
  • splitter – Splitter. ( String )
  • bindingIdentifier – Binding identifier. ( String )
Returns:

Attribute compound. ( AttributeCompound )

4.13.3. Classes

class foundations.parsers.AttributeCompound(**kwargs)[source]

Bases: foundations.dataStructures.Structure

This class represents a storage object for attributes compounds usually encountered in sIBL_GUI Templates files.

Some attributes compounds:

  • Name = @Name | Standard | String | Template Name
  • Background|BGfile = @BGfile
  • showCamerasDialog = @showCamerasDialog | 0 | Boolean | Cameras Selection Dialog

Usage:

AttributeCompound(name="showCamerasDialog", 
                                value="0", 
                                link="@showCamerasDialog", 
                                type="Boolean", 
                                alias="Cameras Selection Dialog")
Parameters:**kwargs – name, value, link, type, alias. ( Key / Value pairs )
class foundations.parsers.SectionsFileParser(file=None, splitters=('=', ':'), namespaceSplitter='|', commentLimiters=(';', '#'), commentMarker='#', quotationMarkers=('"', "'", '`'), rawSectionContentIdentifier='_rawSectionContent', defaultsSection='_defaults')[source]

Bases: foundations.io.File

This class provides methods to parse sections file format files, an alternative configuration file parser is available directly with Python: ConfigParser.ConfigParser.

The parser given by this class has some major differences with Python ConfigParser.ConfigParser:

  • Sections and attributes are stored in their appearance order by default. ( Using Python collections.OrderedDict )
  • A default section ( _default ) will store orphans attributes ( Attributes appearing before any declared section ).
  • File comments are stored inside the SectionsFileParser.comments class property.

  • Sections, attributes and values are whitespaces stripped by default but can also be stored with their leading and trailing whitespaces.
  • Values are quotations markers stripped by default but can also be stored with their leading and trailing quotations markers.
  • Attributes are namespaced by default allowing sections merge without keys collisions.

Usage:

>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sectionsFileParser = SectionsFileParser()
>>> sectionsFileParser.content = content
>>> sectionsFileParser.parse(stripComments=False)
True
>>> sectionsFileParser.sections.keys()
['Section A', 'Section B']
>>> sectionsFileParser.comments 
OrderedDict([('Section A|#0', {'content': 'Comment.', 'id': 0})])
Parameters:
  • file – Current file path. ( String )
  • splitters – Splitter characters. ( Tuple / List )
  • namespaceSplitter – Namespace splitters character. ( String )
  • commentLimiters – Comment limiters characters. ( Tuple / List )
  • commentMarker – Character use to prefix extracted comments idientifiers. ( String )
  • quotationMarkers – Quotation markers characters. ( Tuple / List )
  • rawSectionContentIdentifier – Raw section content identifier. ( String )
  • defaultsSection – Default section name. ( String )
splitters[source]

This method is the property for self.__splitters attribute.

Returns:self.__splitters. ( Tuple / List )
namespaceSplitter[source]

This method is the property for self.__namespaceSplitter attribute.

Returns:self.__namespaceSplitter. ( String )
commentLimiters[source]

This method is the property for self.__commentLimiters attribute.

Returns:self.__commentLimiters. ( Tuple / List )
commentMarker[source]

This method is the property for self.__commentMarker attribute.

Returns:self.__commentMarker. ( String )
quotationMarkers[source]

This method is the property for self.__quotationMarkers attribute.

Returns:self.__quotationMarkers. ( Tuple / List )
rawSectionContentIdentifier[source]

This method is the property for self.__rawSectionContentIdentifier attribute.

Returns:self.__rawSectionContentIdentifier. ( String )
defaultsSection[source]

This method is the property for self.__defaultsSection attribute.

Returns:self.__defaultsSection. ( String )
sections[source]

This method is the property for self.__sections attribute.

Returns:self.__sections. ( OrderedDict / Dictionary )
comments[source]

This method is the property for self.__comments attribute.

Returns:self.__comments. ( OrderedDict / Dictionary )
parsingErrors[source]

This method is the property for self.__parsingErrors attribute.

Returns:self.__parsingErrors. ( List )
parse(orderedDictionary=True, rawSections=None, namespaces=True, stripComments=True, stripWhitespaces=True, stripQuotationMarkers=True, raiseParsingErrors=True)[source]
This method process the file content and extract the sections / attributes
as nested collections.OrderedDict dictionaries or dictionaries.

Usage:

>>> content = ["; Comment.\n", "Attribute 1 = \"Value A\"\n", "Attribute 2 = \"Value B\"\n"]
>>> sectionsFileParser = SectionsFileParser()
>>> sectionsFileParser.content = content
>>> sectionsFileParser.parse(stripComments=False)
True
>>> sectionsFileParser.sections.keys()
['_defaults']
>>> sectionsFileParser.sections["_defaults"].values()
['Value A', 'Value B']
>>> sectionsFileParser.parse(stripQuotationMarkers=False)
True
>>> sectionsFileParser.sections["_defaults"].values()
['"Value A"', '"Value B"']
>>> sectionsFileParser.comments 
OrderedDict([('_defaults|#0', {'content': 'Comment.', 'id': 0})])
>>> sectionsFileParser.parse()
True
>>> sectionsFileParser.sections["_defaults"]
OrderedDict([('_defaults|Attribute 1', 'Value A'), ('_defaults|Attribute 2', 'Value B')])
>>> sectionsFileParser.parse(namespaces=False)
OrderedDict([('Attribute 1', 'Value A'), ('Attribute 2', 'Value B')])
Parameters:
  • orderedDictionary – SectionsFileParser data is stored in collections.OrderedDict dictionaries. ( Boolean )
  • rawSections – Ignored raw sections. ( Tuple / List )
  • namespaces – Attributes and comments are namespaced. ( Boolean )
  • stripComments – Comments are stripped. ( Boolean )
  • stripWhitespaces – Whitespaces are stripped. ( Boolean )
  • stripQuotationMarkers – Attributes values quotation markers are stripped. ( Boolean )
  • raiseParsingErrors – Raise parsing errors. ( Boolean )
Returns:

Method success. ( Boolean )

sectionExists(section)[source]

This method checks if given section exists.

Usage:

>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sectionsFileParser = SectionsFileParser()
>>> sectionsFileParser.content = content
>>> sectionsFileParser.parse()
True
>>> sectionsFileParser.sectionExists("Section A")
True
>>> sectionsFileParser.sectionExists("Section C")
False
Parameters:section – Section to check existence. ( String )
Returns:Section existence. ( Boolean )
attributeExists(attribute, section)[source]

This method checks if given attribute exists.

Usage:

>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sectionsFileParser = SectionsFileParser()
>>> sectionsFileParser.content = content
>>> sectionsFileParser.parse()
True
>>> sectionsFileParser.attributeExists("Attribute 1", "Section A")
True
>>> sectionsFileParser.attributeExists("Attribute 2", "Section A")
False
Parameters:
  • attribute – Attribute to check existence. ( String )
  • section – Section to search attribute into. ( String )
Returns:

Attribute existence. ( Boolean )

getAttributes(section, orderedDictionary=True, stripNamespaces=False)[source]

This method returns given section attributes.

Usage:

>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sectionsFileParser = SectionsFileParser()
>>> sectionsFileParser.content = content
>>> sectionsFileParser.parse()
True
>>> sectionsFileParser.getAttributes("Section A")
OrderedDict([('Section A|Attribute 1', 'Value A')])
>>> sectionsFileParser.getAttributes("Section A", orderedDictionary=False)
{'Section A|Attribute 1': 'Value A'}
>>> sectionsFileParser.getAttributes("Section A", stripNamespaces=True)
OrderedDict([('Attribute 1', 'Value A')])
Parameters:
  • section – Section containing the requested attributes. ( String )
  • orderedDictionary – Use an collections.OrderedDict dictionary to store the attributes. ( String )
  • stripNamespaces – Strip namespaces while retrieving attributes. ( Boolean )
Returns:

Attributes. ( OrderedDict / Dictionary )

getAllAttributes(orderedDictionary=True)[source]

This method returns all sections attributes.

Usage:

>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sectionsFileParser = SectionsFileParser()
>>> sectionsFileParser.content = content
>>> sectionsFileParser.parse()
True
>>> sectionsFileParser.getAllAttributes()
OrderedDict([('Section A|Attribute 1', 'Value A'), ('Section B|Attribute 2', 'Value B')])
>>> sectionsFileParser.getAllAttributes(orderedDictionary=False)
{'Section B|Attribute 2': 'Value B', 'Section A|Attribute 1': 'Value A'}
Parameters:orderedDictionary – Use an collections.OrderedDict dictionary to store the attributes. ( String )
Returns:All sections / files attributes. ( OrderedDict / Dictionary )
getValue(attribute, section, encode=False, default='')[source]

This method returns requested attribute value.

Usage:

>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sectionsFileParser = SectionsFileParser()
>>> sectionsFileParser.content = content
>>> sectionsFileParser.parse()
True
>>> sectionsFileParser.getValue("Attribute 1", "Section A")
Value A
Parameters:
  • attribute – Attribute name. ( String )
  • section – Section containing the searched attribute. ( String )
  • encode – Encode value to unicode. ( Boolean )
  • default – Default return value. ( Object )
Returns:

Attribute value. ( String )

write(namespaces=False, splitter='=', commentLimiter=';', spacesAroundSplitter=True, spaceAfterCommentLimiter=True)[source]
This method writes defined file using SectionsFileParser.sections and
SectionsFileParser.comments class properties content.

Usage:

>>> sections = {"Section A": {"Section A|Attribute 1": "Value A"}, "Section B": {"Section B|Attribute 2": "Value B"}}
>>> sectionsFileParser = SectionsFileParser("SectionsFile.rc")
>>> sectionsFileParser.sections = sections
>>> sectionsFileParser.write()
True
>>> sectionsFileParser.read()
True
>>> print sectionsFileParser.content[0:5]
['[Section A]\n', 'Attribute 1 = Value A\n', '\n', '[Section B]\n', 'Attribute 2 = Value B\n', '\n']
Parameters:
  • namespaces – Attributes are namespaced. ( Boolean )
  • splitter – Splitter character. ( String )
  • commentLimiter – Comment limiter character. ( String )
  • spacesAroundSplitter – Spaces around attributes and value splitters. ( Boolean )
  • spaceAfterCommentLimiter – Space after comments limiter. ( Boolean )
Returns:

Method success. ( Boolean )

class foundations.parsers.PlistFileParser(file=None)[source]

Bases: foundations.io.File

This class provides methods to parse plist files.

Usage:

>>> plistFileParser = PlistFileParser("standard.plist")
>>> plistFileParser.parse()
True
>>> plistFileParser.elements.keys()
['Dictionary A', 'Number A', 'Array A', 'String A', 'Date A', 'Boolean A', 'Data A']
>>> plistFileParser.elements["Dictionary A"]
{'String C': 'My Value C', 'String B': 'My Value B'}
Parameters:file – Current file path. ( String )
elements[source]

This method is the property for self.__elements attribute.

Returns:self.__elements. ( OrderedDict / Dictionary )
parsingErrors[source]

This method is the property for self.__parsingErrors attribute.

Returns:self.__parsingErrors. ( List )
unserializers[source]

This method is the property for self.__unserializers attribute.

Returns:self.__unserializers. ( Dictionary )
parse(raiseParsingErrors=True)[source]

This method process the file content.

Usage:

>>> plistFileParser = PlistFileParser("standard.plist")
>>> plistFileParser.parse()
True
>>> plistFileParser.elements.keys()
['Dictionary A', 'Number A', 'Array A', 'String A', 'Date A', 'Boolean A', 'Data A']
Parameters:raiseParsingErrors – Raise parsing errors. ( Boolean )
Returns:Method success. ( Boolean )
elementExists(element)[source]

This method checks if given element exists.

Usage:

>>> plistFileParser = PlistFileParser("standard.plist")
>>> plistFileParser.parse()
True
>>> plistFileParser.elementExists("String A")
True
>>> plistFileParser.elementExists("String Nemo")
False
Parameters:element – Element to check existence. ( String )
Returns:Element existence. ( Boolean )
filterValues(pattern, flags=0)[source]
This method filters the PlistFileParser.elements() class property elements using given pattern.
This method will return a list of matching elements values, if you want to get only one element value, use the PlistFileParser.getValue() method instead.

Usage:

>>> plistFileParser = PlistFileParser("standard.plist")
>>> plistFileParser.parse()
True
>>> plistFileParser.filterValues(r"String A")
['My Value A']
>>> plistFileParser.filterValues(r"String.*")
['My Value C', 'My Value B', 'My Value A']
Parameters:
  • pattern – Regex filtering pattern. ( String )
  • flags – Regex flags. ( Integer )
Returns:

Values. ( List )

getValue(element)[source]
This method returns the given element value.
If multiple elements with the same name exists, only the first encountered will be returned.

Usage:

>>> plistFileParser = PlistFileParser("standard.plist")
>>> plistFileParser.parse()
True
>>> plistFileParser.getValue("String A")
'My Value A'
Parameters:element – Element to get the value. ( String )
Returns:Element value. ( Object )

Table Of Contents

Previous topic

4.12. foundations.nodes

Next topic

4.14. foundations.pkzip

This Page