Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 930
Lucas Avatar asked Feb 13 '14 22:02

Lucas


People also ask

How do I read a .conf file?

If you need to open a CONF file, you can use TextMate in macOS or GNU Emacs in Linux. Some examples of configuration files include rc. conf for the system startup, syslog. conf for system logging, smb.

How do I use ConfigParser in Python 3?

Read and parse one configuration file, given as a file object. Read configuration from a given string. Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section.

What is config parsing?

ConfigParser is a Python class which implements a basic configuration language for Python programs. It provides a structure similar to Microsoft Windows INI files. ConfigParser allows to write Python programs which can be customized by end users easily.


2 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') 
like image 105
Noel Evans Avatar answered Sep 21 '22 09:09

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')) 
like image 37
Sebastian Avatar answered Sep 23 '22 09:09

Sebastian