-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.py
99 lines (92 loc) · 2.96 KB
/
config.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
mftsc = {
'I' : 'exist',
}
#################################################
### micropython far too simple config file ###
### do not write below this header ###
### do not store collections ###
### usage (add or overwrite config): ###
### >>>import config ###
### >>>config.set('mftsc','I','exist')##
### usage (access config): ###
### >>>config.mftsc['I'] ###
### 'exist' ###
#################################################
import gc
import sys
def set(dictname, key, value, do_reload=True):
newrow = _key_value_dict(key,value)
me = _open_file_to_lines()
dict_start = -1
dict_end = -1
new_dict = False
linx = -1
for rowx, linr in enumerate(me):
if '#######################################' in linr:
new_dict = True
break
if linr[:4] == ' ':
linr = ' ' + ' '.join(linr.split()) + '\n'
else:
linr = ' '.join(linr.split()) + '\n'
if linr[:len(dictname)+4] == dictname + ' = {':
dict_start = rowx
if dict_start != -1:
if " '" + str(key) + "' :" in linr:
linx = rowx
break
if linr == '}\n':
dict_end = rowx
break
result = 0
if new_dict:
newfilerows = _new_dict(dictname,key,value) + me
result = _write_lines_to_file(newfilerows)
elif linx != -1:
me[linx] = newrow
result = _write_lines_to_file(me)
elif dict_end:
me.insert(dict_end,newrow)
result = _write_lines_to_file(me)
if do_reload:
if result:
_reload()
else:
return
else:
return
def _reload():
del sys.modules['libs.config']
# if config is imported by other modules, delete it recursively
for mo in sys.modules:
if 'config' in dir(sys.modules[mo]):
del sys.modules[mo].__dict__['config']
sys.modules[mo].__dict__['config'] = __import__('libs.config').config
gc.collect()
sys.modules['libs.config'] = __import__('libs.config').config
def _new_dict(dictname,key,value):
return [dictname + ' = {\n',
_key_value_dict(key,value),
'}\n']
def _key_value_dict(key,value):
if isinstance(value,str):
return " '" + str(key) + "' : '" + value + "',\n"
else:
return " '" + str(key) + "' : " + str(value) + ",\n"
def _write_lines_to_file(lines):
try:
with open(__file__, 'w') as f:
for line in lines:
f.write(line)
return 1
except Exception:
print("Could not write file: ", __file__)
return 0
def _open_file_to_lines():
conf_lines = []
try:
with open(__file__, 'r') as f:
conf_lines = f.readlines()
except Exception:
print("Could not read file: ", __file__)
return conf_lines