Wednesday, April 23, 2008

Using ConfigParser on StringIO

ConfigParser is one of those bits of Python that is sadly under-documented. Recently I had need of using ConfigParser on a non-file, which meant using StringIO. Sadly, I couldn't find any examples of how to do this. After a little experimenting, I found that this works:

dummy_config = """[pinky]
narf: True
troz: True
"""
config = ConfigParser.ConfigParser()
s = StringIO.StringIO(dummy_config)
config.readfp(s)
print config.sections()

So there you have it: the secret is the readfp() method, which is mentioned in the output of PyDoc, but Google barely knew about.