ConfigParser生成的典型文件如下所示:
[Section]
bar=foo
[Section 2]
bar2= baz
现在,有没有一种方法来索引列表,例如:
[Section 3]
barList={
item1,
item2
}
相关问题:Python的ConfigParser每个节的唯一键
ConfigParser生成的典型文件如下所示:
[Section]
bar=foo
[Section 2]
bar2= baz
现在,有没有一种方法来索引列表,例如:
[Section 3]
barList={
item1,
item2
}
相关问题:Python的ConfigParser每个节的唯一键
当前回答
对split(',')的改进可能是将逗号分隔的值视为CSV文件中的一条记录
import csv
my_list = list(csv.reader([config['Section 3']['barList']], dialect=csv.excel))[0]
您可以配置一种方言来解析任何您喜欢的CSV样式。
其他回答
我过去也遇到过同样的问题。如果需要更复杂的列表,可以考虑通过继承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 ]
你可以在配置文件中使用列表,然后在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
没有什么可以阻止您将列表打包到一个带分隔符的字符串中,然后在从配置中获得字符串后将其解包。如果你这样做,你的配置部分看起来像:
[Section 3]
barList=item1,item2
它并不漂亮,但对于大多数简单的列表来说,它是有用的。
很多人不知道的一件事是允许多行配置值。例如:
;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开头;跟着空格。
我降落在这里想要吃掉这个…
[global]
spys = richard.sorge@cccp.gov, mata.hari@deutschland.gov
答案是用逗号分隔,然后去掉空格:
SPYS = [e.strip() for e in parser.get('global', 'spys').split(',')]
获取一个列表结果:
['richard.sorge@cccp.gov', 'mata.hari@deutschland.gov']
它可能不能准确地回答OP的问题,但可能是一些人正在寻找的简单答案。