Search code examples
pythonpython-2.7configparser

How to read config from string or list?


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?


Solution

  • 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')