How to read config from string or list?

Question:

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?

Asked By: Lucas

||

Answers:

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')
Answered By: Noel Evans

The question was tagged as python-2.7 but just for the sake of completeness: Since 3.2 you can use the ConfigParser function read_string() so you don’t need the StringIO method anymore.

import configparser

s_config = """
[example]
is_real: False
"""
config = configparser.ConfigParser()
config.read_string(s_config)
print(config.getboolean('example', 'is_real'))
Answered By: Sebastian

Python has read_string and read_dict since version 3.2. It does not support reading from lists.

The example shows reading from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section.

#!/usr/bin/env python3

import configparser

cfg_data = {
    'mysql': {'host': 'localhost', 'user': 'user7',
              'passwd': 's$cret', 'db': 'ydb'}
}

config = configparser.ConfigParser()
config.read_dict(cfg_data)

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print(f'Host: {host}')
print(f'User: {user}')
print(f'Password: {passwd}')
print(f'Database: {db}')
Answered By: Jan Bodnar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.