I have the the following config file
# originally this was a (ba)sh config file, now read by python
TEST=123
BAK=.bak
# comment for next line
TEST_2="cool spaced Value"
MY_VAR2="space value" # With a Comment for the value
I have managed to read this with the following code
def parse_lines(self, lines):
pattern = r'[ |\t]*([a-zA-Z_][a-zA-Z0-9_]*)=("([^\\"]|.*)"|([^# \t]*)).*[\r]*\n'
prog = re.compile(pattern)
hash={}
for line in lines:
result = prog.match(line)
if not result is None:
name = result.groups()[0]
if result.groups()[2] is None:
value= result.groups()[3]
else:
value= result.groups()[2]
hash[name]=value
return hash
def read_shell_config(self, filename):
with open(filename) as f:
lines = f.readlines()
hash = self.parse_lines(lines)
return hash
Is there any better way (standard package?) to read a bash config file like the above with python?