Stormer97

itsy bitsey config parser

Dec 10th, 2013
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.56 KB | None | 0 0
  1. # The Itsy Bitsey Config Parser
  2.  
  3. import glob
  4. import os
  5.  
  6. def parse(fname, extension, useFname, combineResults=False):
  7.     # parses a config file, returns the result as a dict
  8.    
  9.     # if useFname is true, it will parse any file with the name
  10.     # fname, and will ignore file extensions
  11.    
  12.     # if useFname is false, it will ignore the name of each file
  13.     # and parse all files with a matching extension
  14.    
  15.     ### syntax ###
  16.     # sect - begins a section
  17.     # endsect - ends a section
  18.     # [foo]=[bar] sets foo equal to bar
  19.  
  20.     ### example of syntax ###
  21.     # file foo.txt
  22.     """
  23.     sect example
  24.     str,cheese=yes
  25.     spinach=nope!
  26.     int,lbsOfCheese=417
  27.     endsect
  28.    
  29.     float,uncatagorizedThing=42
  30.     """
  31.    
  32.     # this will return a dict like this:
  33.     # {name:"foo", sects:{example:{cheese:"yes", spinach:"nope!", lbsOfCheese:417}},
  34.     # nosect:{uncatagorizedThing:42.0}}
  35.    
  36.     # combine results will cause the program to return all of the results form all files in a single
  37.     # dict if set to true, otherwise, it will return a dict where each key corrosponds to the results of each file
  38.    
  39.     fList = [] # list of all files to be parsed
  40.     retVal = {} # setup return value
  41.    
  42.     # decide how glob should get files
  43.     if useFname == True:
  44.         globString = fname + ".*"
  45.     elif useFname == False:
  46.         globString = "*." + extension
  47.     else:
  48.         print "ERROR: IBCP encountered an unhandled useFname argument: ", useFname
  49.         return "ERROR"
  50.    
  51.     # compile list of files to parse
  52.     for files in glob.glob(globString):
  53.         fList.append(files)
  54.    
  55.     if combineResults == True:
  56.         for files in fList:
  57.             f = open(files, 'r')
  58.             foo = doParse(f) # I know this is bad practice, IDGAF
  59.            
  60.             for key in foo:
  61.                 if key not in retVal:
  62.                     retVal[key] = {}
  63.                 retVal[key] = dict(retVal[key].items() + foo[key].items())
  64.                
  65.         return retVal
  66.     else:
  67.         for files in fList:
  68.             f = open(files, 'r')
  69.             foo = doParse(f)
  70.            
  71.             thisKey = files.split('.')[0]
  72.             if thisKey not in retVal:
  73.                 retVal[thisKey] = {}
  74.            
  75.             for key in foo:
  76.                 if key not in retVal[thisKey]:
  77.                     retVal[thisKey][key] = {}
  78.                 retVal[thisKey][key] = dict(retVal[thisKey][key].items() + foo[key].items())
  79.         return retVal
  80.  
  81. def doParse(f):
  82.     # doParse actually does the parsing, and is spun off for modularity
  83.     # f should actuall be the contents of the file
  84.    
  85.     # doParse shouldbe called like this:
  86.     # f=open('something','flag')
  87.     # doParse(f)
  88.        
  89.     inSect = False # currently parsing a section?
  90.     thisSect = '' # name of the current section
  91.     retVal = {} # value to be returned
  92.    
  93.     retVal['nosect'] = {} # add a value for sectionless items
  94.    
  95.     for line in f:
  96.         line = line.rstrip('\n')
  97.         if line != '':
  98.             if line.split(' ')[0] == 'sect':
  99.                 inSect = True
  100.                 thisSect = line.split(' ')[1]
  101.                 retVal[thisSect] = {}
  102.             elif line == 'endsect':
  103.                 inSect = False
  104.                 thisSect = ''
  105.             else:
  106.                 # store the value (line[1]) at the key (line[0])
  107.                 line = lineParser(line)
  108.                 if inSect == True:
  109.                     retVal[thisSect][line[0]]=line[1]
  110.                 else:
  111.                     retVal['nosect'][line[0]]=line[1]
  112.     return retVal
  113.                    
  114. def lineParser(line):
  115.     # parses an individual line
  116.     if line.split(',')[0] == 'int':
  117.         line = line.split(',')[1] # remove the type declaration
  118.         return [line.split('=')[0],int(line.split('=')[1])]
  119.     elif line.split(',')[0] == 'float':
  120.         line = line.split(',')[1] # remove the type declaration
  121.         return [line.split('=')[0],float(line.split('=')[1])]
  122.     elif line.split(',')[0] == 'str':
  123.         line = line.split(',')[1] # remove the type declaration
  124.         return [line.split('=')[0],line.split('=')[1]]
  125.     else:
  126.         return [line.split('=')[0],line.split('=')[1]]
Advertisement
Add Comment
Please, Sign In to add comment