How to read config from string or list?

Lucas picture Lucas · Feb 13, 2014 · Viewed 19.6k times · Source

Is it possible to read the configuration for ConfigParser from a string or list?
Without any kind of temporary file on a filesystem

OR
Is there any similar solution for this?

Answer

Noel Evans picture Noel Evans · Feb 13, 2014

You could use a buffer which behaves like a file: Python 3 solution

import configparser
import io

s_config = """
[example]
is_real: False
"""
buf = io.StringIO(s_config)
config = configparser.ConfigParser()
config.read_file(buf)
print(config.getboolean('example', 'is_real'))

In Python 2.7, this implementation was correct:

import ConfigParser
import StringIO

s_config = """
[example]
is_real: False
"""
buf = StringIO.StringIO(s_config)
config = ConfigParser.ConfigParser()
config.readfp(buf)
print config.getboolean('example', 'is_real')