Page MenuHomec4science

config.py
No OneTemporary

File Metadata

Created
Sun, Dec 22, 15:02

config.py

def parseInt(x):
value = None
try:
value = int(x)
except:
value = None
return value
def parseFloat(x):
value = None
try:
value = float(x)
except:
value = None
return value
class ConfigEntry:
def __init__(self, key, value):
self.key = key
self.value = value
def toString(self, delim = '='):
return "%s %s %s" % (self.key, delim, str(self.value))
def load(line, sep):
v = line.replace(' ', '').split(sep)
if len(v) != 2:
print(v)
return None
value = parseInt(v[1])
if value is None:
value = parseFloat(v[1])
if value is None:
value = v[1] #string
return ConfigEntry(v[0], value)
class Config:
def __init__(self, sep = '=', com = '%', initmap = []):
self.map = initmap
self.sep = sep
self.com = com
def load(self, filename):
self.map = []
reader = open(filename, 'r')
for line in reader:
if line: #eof
entry = None
if line.startswith(self.com):
entry = line[1:-1]
else:
entry = ConfigEntry.load(line[:-1], self.sep)
if entry is not None:
self.map.append(entry)
else:
print("Line \"", line[:-1], "\" format not valid, skipping it")
reader.close()
def save(self, filename):
writer = open(filename, 'w')
writer.write(str(self))
writer.close()
def __str__(self):
out = ""
for entry in self.map:
if isinstance(entry, str):
out += ("%s%s\n" % (self.com, entry))
elif isinstance(entry, ConfigEntry):
out += ("%s\n" % entry.toString(self.sep))
return out
def __getitem__(self, key):
for entry in self.map:
if isinstance(entry, ConfigEntry) and entry.key == key:
return entry.value
def __setitem__(self, key, value):
for entry in self.map:
if isinstance(entry, ConfigEntry) and entry.key == key:
entry.value = value

Event Timeline