Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse shell style config in python

Tags:

python

all,

I'm working on some scripts, I have a shell style config file like this:

A=1
B=2

Now I have to write a python script, and use this config file for some value. Someone said to use ConfigureParser module of python(codes like this), but I got error.

>>> import ConfigParser
>>> cf = ConfigParser.ConfigParser()
>>> cf.read("config")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ConfigParser.py", line 305, in read
    self._read(fp, filename)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ConfigParser.py", line 512, in _read
    raise MissingSectionHeaderError(fpname, lineno, line)
ConfigParser.MissingSectionHeaderError: File contains no section headers.
file: config, line: 1
'A=1\n'

I can't use python ConfigParser style config file, which means the config file is just like above, could not change it. So how to parse shell style config in python? Thank you~

like image 467
batmancn Avatar asked Sep 05 '26 23:09

batmancn


1 Answers

Try using the config.read_string() method to parse a config string instead of a filename. You can then use a string header to change the format of the config file in-memory:

import configparser

# Slurp in file contents
with open('example.cfg') as ec:
    cfg_data = ec.read()

# Insert a section header
cfg_data = "[default]\n\n" + cfg_data


# Now read the configuration:
cfgparser = configparser.ConfigParser()
cfgparser.read_string(cfg_data, source='example.cfg')
like image 124
aghast Avatar answered Sep 07 '26 13:09

aghast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!