forked from bmajoros/python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConfigFile.py
executable file
·63 lines (55 loc) · 2.21 KB
/
ConfigFile.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
#====================================================================
# Copyright (C)2016 William H. Majoros ([email protected]).
# This is OPEN SOURxCE SOFTWARE governed by the Gnu General Public
# License (GPL) version 3, as described at www.opensource.org.
#====================================================================
from __future__ import (absolute_import, division, print_function,
unicode_literals, generators, nested_scopes, with_statement)
from builtins import (bytes, dict, int, list, object, range, str, ascii,
chr, hex, input, next, oct, open, pow, round, super, filter, map, zip)
import re
######################################################################
# Attributes:
# hash
# Methods:
# configFile=ConfigFile(filename)
# value=configFile.lookup(key)
# value=configFile.lookupOrDie(key)
# list=configFile.lookupList(key,sep=", ")
# Private methods:
# self.load(filename)
######################################################################
class ConfigFile:
"""ConfigFile stores variable assignments as key-value pairs
in a hash
"""
def __init__(self,filename):
self.hash={}
self.load(filename)
def lookupList(self,key,sep=",\s*"):
value=self.lookup(key)
if(value is None): return value
return re.split(sep, value)
def lookupListOrDie(self,key,sep=",\s*"):
if(key not in self.hash):
raise Exception(f"{key} not defined in config file\n")
return self.lookupList(key, sep)
def lookup(self,key):
return self.hash.get(key)
def lookupOrDie(self,key):
if(key not in self.hash):
raise Exception(f"{key} not defined in config file\n")
return self.hash[key]
def load(self,filename):
hash=self.hash
with open(filename,"r") as fh:
while(True):
line=fh.readline()
if(not line): break
match=re.search("^(.*)#",line);
if(match): line=match.group(1)
match=re.search("^\s*(\S+)\s*=\s*(\S+)",line);
if(match):
key=match.group(1)
value=match.group(2)
hash[key]=value