comparison python/simpleini.py @ 115:c499f5a598cf

make variable interpolation sorta work; the nonce thing probably isnt the best idea
author Jeff Hammel <jhammel@mozilla.com>
date Thu, 02 Dec 2010 17:16:53 -0800
parents 9b193312ceba
children
comparison
equal deleted inserted replaced
114:9b193312ceba 115:c499f5a598cf
1 #!/usr/bin/env python 1 #!/usr/bin/env python
2 2
3 import os 3 import os
4 4
5 def read(fp, variables=None, default='DEFAULT', 5 def read(fp, variables=None, default='DEFAULT',
6 comments=';#', separators=('=', ':'), strict=True): 6 comments=';#', separators=('=', ':'),
7 interpolate=True, strict=True):
7 """ 8 """
8 read an .ini file and return a list of [(section, values)] 9 read an .ini file and return a list of [(section, values)]
9 - fp : file pointer or name to read 10 - fp : file pointer or name to read
10 - variables : default set of variables 11 - variables : default set of variables
11 - default : name of the section for the default section 12 - default : name of the section for the default section
92 93
93 # interpret the variables 94 # interpret the variables
94 def interpret_variables(global_dict, local_dict): 95 def interpret_variables(global_dict, local_dict):
95 variables = global_dict.copy() 96 variables = global_dict.copy()
96 variables.update(local_dict) 97 variables.update(local_dict)
97 # TODO: string intepolation 98
99 # string intepolation
100 if interpolate:
101 nonce = '__s__'
102 assert nonce not in global_dict
103 global_dict[nonce] = '%s'
104 for key, value in variables.items():
105 try:
106 value = value.replace('%s', '%(__s__)s') % global_dict
107 variables[key] = value
108 except:
109 if strict:
110 del global_dict[nonce]
111 raise Exception("could not intepolate variable %s: %s" % (key, value))
112 pass
113
114 del global_dict[nonce]
98 return variables 115 return variables
99 116
100 sections = [(i, interpret_variables(variables, j)) for i, j in sections] 117 sections = [(i, interpret_variables(variables, j)) for i, j in sections]
101 return sections 118 return sections
102 119
103 if __name__ == '__main__': 120 if __name__ == '__main__':
104 import sys 121 import sys
105 for i in sys.argv[1:]: 122 for i in sys.argv[1:]:
106 print read(i) 123 path = os.path.abspath(i)
124 print read(i, strict=False, variables=dict(here=os.path.dirname(path)))