This snippet provides a parser and serializer for KiCAD schematic symbol libraries and DCM symbol documentation libraries. It will parse the KiCAD libraries into a number of records, consisting of a list of lines. An extended version of this snippet has been used in my KiCADSamacSysImporter project
__author__ = "Uli Köhler" __license__ = "CC0 1.0 Universal" class KiCADDocLibrary(object): def __init__(self, records=[]): self.records = records @staticmethod def read(file): # A record is everything between '$CMP ...' line and '$ENDCMP' line records = [] current_record = None for line in file: line = line.strip() if line.startswith('$CMP '): current_record = [] # Add line to record if we have any current record if current_record is not None: current_record.append(line) if line.startswith("$ENDCMP"): if current_record is not None: records.append(current_record) current_record = None return KiCADDocLibrary(records) def write(self, out): # Write header out.write("EESchema-DOCLIB Version 2.0\n") # Write records for rec in self.records: out.write("#\n") for line in rec: out.write(line) out.write("\n") # Write footer out.write("#\n#End Doc Library\n") class KiCADSchematicSymbolLibrary(object): def __init__(self, records=[]): self.records = records @staticmethod def read(file): # A record is everything between 'DEF ...' line and 'ENDDEF' line records = [] current_record = None current_comment_lines = [] # for line in file: line = line.strip() if line.startswith("#encoding"): continue # Ignore - we always use #encoding utf-8 # Comment line processing if line.startswith("#"): current_comment_lines.append(line) # Start of record if line.startswith('DEF '): current_record = current_comment_lines current_comment_lines = [] # Add line to record if we have any current record if current_record is not None: current_record.append(line) if line.startswith("ENDDEF"): if current_record is not None: records.append(current_record) current_record = None # Clear comment lines # We can only do this now to avoid clearing them before # they are used in the DEF clause if not line.startswith("#"): current_comment_lines = [] return KiCADSchematicSymbolLibrary(records) def write(self, out): # Write header out.write("EESchema-LIBRARY Version 2.4\n#encoding utf-8\n") # Write records for rec in self.records: for line in rec: out.write(line) out.write("\n") # Write footer out.write("#\n#End Library\n")