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

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

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

[Section 3]
barList={
    item1,
    item2
}

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


当前回答

json。负载& ast.literal_eval似乎工作,但配置中的简单列表将每个字符视为字节,因此返回偶数方括号....

这意味着如果配置字段值= [1,2,3,4,5]

然后config.read (* . cfg) config['fieldValue'][0]返回[代替1

其他回答

没有什么可以阻止您将列表打包到一个带分隔符的字符串中,然后在从配置中获得字符串后将其解包。如果你这样做,你的配置部分看起来像:

[Section 3]
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类在其他地方完成的解析工作。

对split(',')的改进可能是将逗号分隔的值视为CSV文件中的一条记录

import csv
my_list = list(csv.reader([config['Section 3']['barList']], dialect=csv.excel))[0]

您可以配置一种方言来解析任何您喜欢的CSV样式。

你可以在配置文件中使用列表,然后在python中解析它

from ast import literal_eval

literal_eval("[1,2,3,4]")

import json

json.loads("[1,2,3,4]")

你也可以在你的配置文件后面使用json文件,像这样:

your config file :
[A]
json_dis = .example.jason
--------------------
your code :
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# getting items of section A
config.items('A')
# result is a list of key-values

配置解析器只支持基本类型的序列化。对于这种需求,我会使用JSON或YAML。