Lists in Configparser

Lists in ConfigParser

There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like:

[Section 3]
barList=item1,item2

It's not pretty but it's functional for most simple lists.

Python - How to read list values from config file (INI) using python configParser

You are getting a string object and not a list. You can either process the string to a list

Ex:

config = configparser.ConfigParser()
config.read(text.conf)
header = [i.strip("'") for i in config['CSV'].get('headers').split(",")]

Or add [] --> headers = ['Column1','Column2','Column3'] to the config file and use the ast module to convert it to a list

Ex:

headers = ['Column1','Column2','Column3']
print(ast.literal_eval(config['CSV']['headers']))

How can I read in lists within a list using ConfigParser() in Python?

You can store a list (or list of lists or dict or whatever) as a string, and use ast to recover it.

Config:

[INPUT]
values = [[40000, 60000], [70000, 80000]]

And script (simplified as reading string variable from config is not a problem):

import ast
list_in_list = ast.literal_eval(string_var_read_from_config)

Getting a list from a config file with ConfigParser

You cannot use the python object like a list in the value for the config file. But you can ofcourse have them as comma separated values and once you get it do a split

[filters]
filtersToCheck = foo,192.168.1.2,barbaz

and do

filtersToCheck = value.split(',')

The other approach is ofcourse, subclassing SafeConfigParser class and removing the [ and ] and constructing the list. You termed this as ugly, but this is a viable solution.

The third way is to use Python module as a config file. Projects do this. Just have the filtersToCheck as a variable available from your config.py module and use the list object. That is a clean solution. Some people are concerned about using python file as config file (terming it as security hazard, which is somewhat an unfounded fear), but there also this group who believe that users should edit config files a not python files which serve as config file.

Parse numbers and lists from config files with configparser

Best I can do is this (though it's kinda hacky and probably dangerous too):

for key, value in settings.items():
try: # will handle both ints and floats, even tuples with ints/floats
settings[key] = eval(value)
except NameError: # this means it's a string or a tuple with strings
get_val = list(map(str.strip, value.split(",")))
settings[key] = get_val if get_val[1:] else get_val[0]

This will work correctly for ints, floats as well as your comma separated values (it will evaluated it as a tuple, I guess that should be fine though I added a condition for that anyway).

Get a list from config.ini file

Use str.split:

List = List.split(',')

string = 'a, b, c'
print(string.split(','))
>> ['a', 'b', 'c']

How to set a list (not a string) on a configparser parameter

You can convert python valid string object to actaul by using of ast.literal_eval

import ast
l1 = "['p1', 'p2', 'p3']"
l2 = ast.literal_eval(l1)
>>> l2
>>> ['p1', 'p2', 'p3']
>>> type(l2)
>>> <class 'list'>

receiving lists using config parser

Go through This video https://www.youtube.com/watch?v=jBwfq6UMxkY for better understanding of ConfigParser. For your current problem you can format the string value from ini file as per your need.

print(config['Airport']['YMML'].split(','))

Python configparser: get list of unused entries

I have written a solution. It is not too elegant but it works. You need to create a child class from RawConfigParser class and create a dict variable in your class and extend the get, _get methods. As you can see below when you use the get, getint, getfloat, getboolean methods to get a value of variable then the related method appends the section and variable to your dict. When you call the get_unused_keys method, it will filter the all available options in a section with the already used options and gives the unused options.

Complete code:

try:
import ConfigParser as Cp
except ImportError:
import configparser as Cp

class ConfigParser(Cp.RawConfigParser):
"""
ConfigParser class contains the all ConfigParser related implementations.
"""

used_vars = {}

def get_unused_keys(self, section):
all_sections = self.options(section)
unused_options = [x for x in all_sections if x not in self.used_vars[section]]
return unused_options

def get(self, section, option, *, raw=False, vars=None, fallback=Cp._UNSET):
if section not in self.used_vars:
self.used_vars[section] = [option]
else:
self.used_vars[section].append(option)
return super().get(section, option, raw=raw, vars=vars, fallback=fallback)

def _get(self, section, conv, option, **kwargs):
if section not in self.used_vars:
self.used_vars[section] = [option]
else:
self.used_vars[section].append(option)
return super()._get(section, conv, option, **kwargs)

parser = ConfigParser()
parser.read("test.ini")

p1 = parser.getint(section="TEST", option="param1")
print("TEST section - param1 = {}".format(p1))
p2 = parser.getboolean(section="TEST", option="param2")
print("TEST section - param2 = {}".format(p2))
print("Unused options in 'TEST' section: {}".format(parser.get_unused_keys("TEST")))
print("")
par2 = parser.get(section="TEST_SEC", option="param2")
print("TEST_SEC section - param2 = {}".format(par2))
print("Unused options in 'TEST_SEC' section: {}".format(parser.get_unused_keys("TEST_SEC")))

Used ini file:

[TEST]
param1 = 1
param2 = True
param3 = 3
param4 = False

[TEST_SEC]
param1 = 89
param2 = Hello World
param3 = 655

OUTPUT:

>>> python3 test.py 
TEST section - param1 = 1
TEST section - param2 = True
Unused options in 'TEST' section: ['param3', 'param4']

TEST_SEC section - param2 = Hello World
Unused options in 'TEST_SEC' section: ['param1', 'param3']

FYI:

You shouldn't use DEFAULT as name of section because it is a special section and you can get unexpected behavior. I have added _get method to my implementations. If you check the original implementation of ConfigParser, you can see all type specific getter use this method so it is enough to change. It means now the implementation supports getint, getfloat, getboolean methods as well.
I hope my answer help you!



Related Topics



Leave a reply



Submit