You could add a 'mock section' and still use ConfigParser
# tested with python 2.7.2
import ConfigParser
from functools import partial
from itertools import chain
class Helper:
def __init__(self, section, file):
self.readline = partial(next, chain(("[{0}]\n".format(section),), file, ("",)))
config = ConfigParser.RawConfigParser(allow_no_value=True)
with open("essconfig.cfg") as ifh:
config.readfp(Helper("Foo", ifh))
print(config.get("Foo", "old_passwords"))
The config file was
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
skip-external-locking
old_passwords = 1
skip-bdb
skip-innodb
Gribouillis
Posting Maven
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11
Question Answered as of 7 Months Ago by
Gribouillis This class should work for very old versions of python
class Helper:
def __init__(self, section, file):
self.section = "[%s]\n" % section
self.file = file
self.state = -1
def readline(self):
if self.state:
if self.state < 0:
self.state = 0
return self.section
else:
return ""
else:
s = self.file.readline()
if not s:
self.state = 1
return s
Why don't you upgrade ? Python 2.2 is a dinosaur :)
Gribouillis
Posting Maven
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11
Try
try:
ifh = open("essconfig.cfg", "rb")
config.readfp(Helper("Foo", ifh))
finally:
ifh.close()
but I don't know how configparser was in python 2.2.1
Gribouillis
Posting Maven
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11
BTW, would you recommend using stringIO to achieve the same?
Given that configuration files are often small files, I would say why not ? Loading a small file in memory is not a very expensive operation.
Gribouillis
Posting Maven
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11