Retrieving a List from a Configuration File Using ConfigParser in Python

I have something like this in my configuration file (configuration option that contains a list of lines):

[filters] filtersToCheck = ['foo', '192.168.1.2', 'barbaz'] 

is there a more elegant (built-in) way to get a list from filtersToCheck instead of removing brackets, single quotes, spaces and then using split () to do this? Maybe another module? Thanks..

(using python3)

+6
source share
3 answers

You cannot use a python object as a list in the value for the configuration file. But you can, of course, have them as comma-separated values, and as soon as you get it, do the splitting

 [filters] filtersToCheck = foo,192.168.1.2,barbaz 

and do

 filtersToCheck = value.split(',') 

Another approach is, for example, a subclass of SafeConfigParser and deleting [and] and building a list. You called it ugly, but it is a viable solution.

The third way is to use the Python module as a configuration file. Projects do it. Just use the ToCheck filters as a variable accessible from your config.py module and use a list object. This is a clean solution. Some people are worried about using the python file as a configuration file (considering it a security risk, which is an unreasonable fear), but also this group, who believe that users should edit the configuration files and not the python files that serve as the configuration file.

+11
source

Take a look at configobj .

+2
source
 ss = """a_string = 'something' filtersToCheck = ['foo', '192.168.1.2', 'barbaz'] a_tuple = (145,'kolo',45)""" import re regx = re.compile('^ *([^= ]+) *= *(.+)',re.MULTILINE) for mat in regx.finditer(ss): x = eval(mat.group(2)) print 'name :',mat.group(1) print 'value:',x print 'type :',type(x) print 

result

 name : a_string value: something type : <type 'str'> name : filtersToCheck value: ['foo', '192.168.1.2', 'barbaz'] type : <type 'list'> name : a_tuple value: (145, 'kolo', 45) type : <type 'tuple'> 

Then

 li = [ (mat.group(1),eval(mat.group(2))) for mat in regx.finditer(ss)] print li 

result

 [('a_string', 'something'), ('filtersToCheck', ['foo', '192.168.1.2', 'barbaz']), ('a_tuple', (145, 'kolo', 45))] 
+1
source

Source: https://habr.com/ru/post/893134/


All Articles