112
|
1 #!/usr/bin/env python
|
|
2
|
|
3 import os
|
|
4
|
|
5 def read(fp, comments=';#', separators=('=', ':')):
|
|
6
|
|
7 if isinstance(fp, basestring):
|
|
8 fp = file(fp)
|
|
9
|
|
10 sections = []
|
|
11 key = value = None
|
|
12
|
|
13 for line in fp.readlines():
|
|
14
|
|
15 stripped = line.strip()
|
|
16
|
|
17 # ignore blank lines
|
|
18 if not stripped:
|
|
19 continue
|
|
20
|
|
21 # ignore comment lines
|
|
22 if stripped[0] in comments:
|
|
23 continue
|
|
24
|
|
25 # check for a new section
|
|
26 if len(stripped) > 2 and stripped[0] == '[' and stripped[-1] == ']':
|
|
27 section = stripped[1:-1].strip()
|
|
28 sections.append((section, {}))
|
|
29 key = value = None
|
|
30 # TODO: should probably make sure this section doesn't already exist
|
|
31 continue
|
|
32
|
|
33 # if there aren't any sections yet, something bad happen
|
|
34 if not sections:
|
|
35 raise Exception('No sections yet :(')
|
|
36
|
|
37 # (key, value) pair
|
|
38 for separator in separators:
|
|
39 if separator in stripped:
|
|
40 key, value = stripped.split(separator, 1)
|
|
41 key = key.strip()
|
|
42 value = value.strip()
|
|
43 sections[-1][1][key] = value
|
|
44 # TODO: should probably make sure this key isn't already in the section
|
|
45 break
|
|
46 else:
|
|
47 # continuation line ?
|
|
48 if line[0].isspace() and key:
|
|
49 value = '%s%s%s' % (value, os.linesep, stripped)
|
|
50 sections[-1][1][key] = value
|
|
51 else:
|
|
52 # something bad happen!
|
|
53 raise Exception("Not sure what you're trying to do")
|
|
54
|
|
55 return sections
|
|
56
|
|
57 if __name__ == '__main__':
|
|
58 import sys
|
|
59 for i in sys.argv[1:]:
|
|
60 print read(i)
|