ConfigParser生成的典型文件如下所示:

[Section]
bar=foo
[Section 2]
bar2= baz

现在,有没有一种方法来索引列表,例如:

[Section 3]
barList={
    item1,
    item2
}

相关问题:Python的ConfigParser每个节的唯一键


当前回答

很多人不知道的一件事是允许多行配置值。例如:

;test.ini
[hello]
barlist = 
    item1
    item2

config.get('hello','barlist')的值现在将是:

"\nitem1\nitem2"

你可以很容易地用splitlines方法进行分割(不要忘记过滤空项)。

如果我们看看像金字塔这样的大框架,他们正在使用这种技术:

def aslist_cronly(value):
    if isinstance(value, string_types):
        value = filter(None, [x.strip() for x in value.splitlines()])
    return list(value)

def aslist(value, flatten=True):
    """ Return a list of strings, separating the input based on newlines
    and, if flatten=True (the default), also split on spaces within
    each line."""
    values = aslist_cronly(value)
    if not flatten:
        return values
    result = []
    for value in values:
        subvalues = value.split()
        result.extend(subvalues)
    return result

我自己,我可能会扩展ConfigParser,如果这是一个常见的事情为你:

class MyConfigParser(ConfigParser):
    def getlist(self,section,option):
        value = self.get(section,option)
        return list(filter(None, (x.strip() for x in value.splitlines())))

    def getlistint(self,section,option):
        return [int(x) for x in self.getlist(section,option)]

注意,在使用这种技术时需要注意一些事情

作为项目的新行应该以空格开始(例如空格或制表符) 下面所有以空格开头的行都被认为是前一项的一部分。如果它有一个=号或者如果它以a开头;跟着空格。

其他回答

在我的项目中,我用带键没有值的section完成了类似的任务:

import configparser

# allow_no_value param says that no value keys are ok
config = configparser.ConfigParser(allow_no_value=True)

# overwrite optionxform method for overriding default behaviour (I didn't want lowercased keys)
config.optionxform = lambda optionstr: optionstr

config.read('./app.config')

features = list(config['FEATURES'].keys())

print(features)

输出:

['BIOtag', 'TextPosition', 'IsNoun', 'IsNomn']

app.config:

[FEATURES]
BIOtag
TextPosition
IsNoun
IsNomn

这些回答中没有提到ConfigParser()的转换器kwarg,这令人相当失望。

根据文档,您可以向ConfigParser传递一个字典,它将为解析器和节代理添加一个get方法。对于列表:

example.ini

[Germ]
germs: a,list,of,names, and,1,2, 3,numbers

解析器的例子:

cp = ConfigParser(converters={'list': lambda x: [i.strip() for i in x.split(',')]})
cp.read('example.ini')
cp.getlist('Germ', 'germs')
['a', 'list', 'of', 'names', 'and', '1', '2', '3', 'numbers']
cp['Germ'].getlist('germs')
['a', 'list', 'of', 'names', 'and', '1', '2', '3', 'numbers']

这是我个人最喜欢的,因为不需要子类化,我不需要依赖最终用户来完美地编写JSON或可以由ast.literal_eval解释的列表。

我更喜欢的另一种方法,就是分割这些值,例如:

#/path/to/config.cfg
[Numbers]
first_row = 1,2,4,8,12,24,36,48

可以像这样加载到字符串或整数列表中,如下所示:

import configparser

config = configparser.ConfigParser()
config.read('/path/to/config.cfg')

# Load into a list of strings
first_row_strings = config.get('Numbers', 'first_row').split(',')

# Load into a list of integers
first_row_integers = [int(x) for x in config.get('Numbers', 'first_row').split(',')]

这种方法可以避免将值包装在括号中以JSON形式加载。

我过去也遇到过同样的问题。如果需要更复杂的列表,可以考虑通过继承ConfigParser来创建自己的解析器。然后你会用它覆盖get方法:

    def get(self, section, option):
    """ Get a parameter
    if the returning value is a list, convert string value to a python list"""
    value = SafeConfigParser.get(self, section, option)
    if (value[0] == "[") and (value[-1] == "]"):
        return eval(value)
    else:
        return value

有了这个解决方案,您还可以在配置文件中定义字典。

但是要小心!这并不安全:这意味着任何人都可以通过您的配置文件运行代码。如果安全性在你的项目中不是问题,我会考虑直接使用python类作为配置文件。下面的文件比ConfigParser文件更强大、更可消耗:

class Section
    bar = foo
class Section2
    bar2 = baz
class Section3
    barList=[ item1, item2 ]
import ConfigParser
import os

class Parser(object):
    """attributes may need additional manipulation"""
    def __init__(self, section):
        """section to retun all options on, formatted as an object
        transforms all comma-delimited options to lists
        comma-delimited lists with colons are transformed to dicts
        dicts will have values expressed as lists, no matter the length
        """
        c = ConfigParser.RawConfigParser()
        c.read(os.path.join(os.path.dirname(__file__), 'config.cfg'))

        self.section_name = section

        self.__dict__.update({k:v for k, v in c.items(section)})

        #transform all ',' into lists, all ':' into dicts
        for key, value in self.__dict__.items():
            if value.find(':') > 0:
                #dict
                vals = value.split(',')
                dicts = [{k:v} for k, v in [d.split(':') for d in vals]]
                merged = {}
                for d in dicts:
                    for k, v in d.items():
                        merged.setdefault(k, []).append(v)
                self.__dict__[key] = merged
            elif value.find(',') > 0:
                #list
                self.__dict__[key] = value.split(',')

所以现在我的config.cfg文件,看起来像这样:

[server]
credentials=username:admin,password:$3<r3t
loggingdirs=/tmp/logs,~/logs,/var/lib/www/logs
timeoutwait=15

可以解析为我的小项目所需的足够细粒度的对象。

>>> import config
>>> my_server = config.Parser('server')
>>> my_server.credentials
{'username': ['admin'], 'password', ['$3<r3t']}
>>> my_server.loggingdirs:
['/tmp/logs', '~/logs', '/var/lib/www/logs']
>>> my_server.timeoutwait
'15'

这是为了非常快速地解析简单的配置,您失去了获取int、bool和其他类型输出的所有能力,既没有转换从Parser返回的对象,也没有重新执行Parser类在其他地方完成的解析工作。