config.py
1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# -*- coding: utf-8 -*-
import re
import os
SECTION = re.compile("^\[(.*)\]$")
SUBSECTION = re.compile("^\{(.*)\}$")
ENTRY = re.compile("^([^=\s]+)\s*=\s*([^=]+)\s*$")
def cut_comment(s):
return s.split("#")[0]
class Config:
def __init__(self, path):
section = None
subsection = None
self.d = {}
with open(path) as f:
for line in f:
line = cut_comment(line).strip()
m = SECTION.search(line)
if m is not None:
section = m.group(1)
subsection = None
continue
m = SUBSECTION.search(line)
if m is not None:
subsection = m.group(1)
continue
m = ENTRY.search(line)
if m is not None:
key = m.group(1)
val = m.group(2)
if subsection == "paths":
# print path, val, os.path.join(path, val)
val = self.relative_path(val, path)
if section is not None:
self.d[section + "." + key] = val
else:
self.d[key] = val
def relative_path(self, path, ref):
return os.path.join(os.path.dirname(ref), path)
def __getitem__(self, key):
return self.d[key]