简体   繁体   中英

Getting a list from a config file with ConfigParser

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

[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 the brackets, single-quotes, spaces and then using split() to do that? Maybe a different module?

(Using python3.)

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.

Have a look at configobj .

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))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM