aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--confparser.py27
-rw-r--r--confparser_test.py49
2 files changed, 76 insertions, 0 deletions
diff --git a/confparser.py b/confparser.py
new file mode 100644
index 0000000..e43443b
--- /dev/null
+++ b/confparser.py
@@ -0,0 +1,27 @@
+#!python3
+
+__all__ = ['read_conf']
+
+import csv
+
+class conf_dialect(csv.Dialect):
+ delimiter = '='
+ quotechar = '"'
+ escapechar = '\\'
+ doublequote = True
+ skipinitialspace = True
+ lineterminator = '\n'
+ quoting = csv.QUOTE_MINIMAL
+
+def genestrip(geneorg):
+ for line in geneorg:
+ line = line.strip()
+ if not len(line) or line.startswith('#'):
+ continue
+ yield line
+
+def read_conf(filename):
+ with open(filename, 'r', encoding='utf8') as linegen:
+ reader = csv.reader(genestrip(linegen), dialect=conf_dialect)
+ dic = {row[0].strip(): row[1] for row in reader if len(row) >= 2}
+ return dic
diff --git a/confparser_test.py b/confparser_test.py
new file mode 100644
index 0000000..d5044f2
--- /dev/null
+++ b/confparser_test.py
@@ -0,0 +1,49 @@
+#!python3
+
+import tempfile
+import confparser
+
+def parse_test():
+ msg = '''\
+# comment with ":" and "=" in it: :=
+a= Test
+
+ # another comment with space and := tada
+b = "Test of a long string"
+
+# third comment
+c=What do YOU want ? ''
+d = value with a squote at the end '
+e = value with a dquote at the end "
+f = "value with a \\" inside"
+x.y.z = there you can have a full tree of parameters
+'''
+ with tempfile.NamedTemporaryFile(mode='w', encoding='utf8') as f:
+ f.write(msg)
+ print('Following lines have been written to the file:')
+ print('-'*40)
+ print(msg)
+ print('-'*40)
+ f.flush()
+ dic = confparser.read_conf(f.name)
+ print('read dic:', dic)
+ dictest = {
+ 'a': 'Test',
+ 'b': 'Test of a long string',
+ 'c': "What do YOU want ? ''",
+ 'd': 'value with a squote at the end \'',
+ 'e': 'value with a dquote at the end "',
+ 'f': 'value with a " inside',
+ 'x.y.z': 'there you can have a full tree of parameters',
+ }
+ if dic != dictest:
+ a = set(dictest.keys())
+ b = set(dic.keys())
+ if a != b:
+ diff = a.difference(b).union(b.difference(a))
+ raise Exception('not same keys between two dicts:', diff)
+ a = set(dictest.values())
+ b = set(dic.values())
+ if a != b:
+ diff = a.difference(b).union(b.difference(a))
+ raise Exception('differences between two set of values:', diff)