def config( file ):
"""config --- Read a config file in cfg format.
(dict) dict config( (string) file )"""
import re
"""_checktype --- Help function to get the right data type.
(bool) bool _checktype( (string) Type, (string) String )"""
def _checktype( Type, String ):
if Type == 'int':
regexp = re.compile('^\d+$')
elif Type == 'float':
regexp = re.compile('^\d+\.\d+$')
elif Type == 'bool':
regexp = re.compile('^(True|False)$')
elif Type == 'tuple':
regexp = re.compile('^\(.*\)$')
elif Type == 'dict':
regexp = re.compile('^\{.*\}$')
elif Type == 'list':
regexp = re.compile('^\[.*\]$')
if regexp.match( str(String) ) != None:
return True
else:
return False
conf = {} # empty dictionary
# Open the config file and loop all lines.
fh = open( file )
for line in fh:
# Remove spaces from the begin and end of the line.
line = line.strip()
# Ignore comment lines.
if not line or line.startswith('#') or line.startswith(';'):
continue
# Define the regexp object to split keys(1)/value(2) pairs.
match = re.match( r'(.*?)\s*=\s*(.*)$', line )
assert match, "Syntax error in following line: %s" % line
# String is the default data type.
value = str(match.group(2))
# Convert the value into the right data type.
if _checktype( 'int', value ):
value = int(eval(value)) # integer found
if _checktype( 'float', value ):
value = float(eval(value)) # float found
if _checktype( 'tuple', value ):
value = tuple(eval(value)) # tuple found
if _checktype( 'dict', value ):
value = dict(eval(value)) # dictionary found
if _checktype( 'list', value ):
value = list(eval(value)) # list found
if _checktype( 'bool', value ):
value = bool(eval(value)) # bolean found
# Save Keys/Value pairs into dictionary 'conf'.
conf[match.group(1)] = value
# Close file and return the dictionary.
fh.close()
return conf