-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig4star.py
47 lines (41 loc) · 1.5 KB
/
config4star.py
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
def writeconf(fname, config_dict):
with open(fname, 'wt') as out_file:
for secname, section in config_dict.items():
out_file.write(f'{secname} {{\n')
for varname, var in section.items():
out_file.write(f' {varname} = "{var}";\n')
out_file.write(f'}};\n\n')
def readconf(fname):
nonprint = ' \t\n'
with open(fname, 'rt') as in_file:
buf = in_file.read(5000).replace('\n', '') # Read original file stripping EoL chars
scopes = {}
scopename = ""
reading_scope = False
for c in buf:
if c == "{": # Scope starts
reading_scope = True
scopes[scopename] = ""
elif c == "}": # Scope ends
reading_scope = False
scopename = ""
elif reading_scope:
scopes[scopename] += c
else:
if c in "; \n\t":
continue
scopename += c
for sn in list(scopes.keys()):
text = scopes[sn]
scopes[sn] = {}
for line in text.split(";"):
line = line.strip()
if "=" in line:
k, v = line.split("=", 1)
scopes[sn][k.strip(nonprint)] = v.strip(nonprint).lstrip('"').rstrip('"')
return scopes
def test_readconf():
fname = 'test.conf'
scopes = readconf(fname)
print(scopes['global']['db_connect_string'])
writeconf(fname + "_new", scopes)