ConfigParser 中的列表
典型的 ConfigParser 生成的文件如下所示:
[Section]
bar=foo
[Section 2]
bar2= baz
现在,有没有一种方法可以索引列表,例如:
[Section 3]
barList={
item1,
item2
}
The typical ConfigParser generated file looks like:
[Section]
bar=foo
[Section 2]
bar2= baz
Now, is there a way to index lists like, for instance:
[Section 3]
barList={
item1,
item2
}
Related question: Python’s ConfigParser unique keys per section
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
如果你想字面上传递一个列表,那么你可以使用:
例如配置:
代码是:
输出:
If you want to literally pass in a list then you can use:
For example configuration:
The code is:
output:
我登陆这里寻求消耗这个...
答案是将其拆分为逗号并去掉空格:
要获得列表结果:
它可能无法准确回答OP的问题,但可能是一些人正在寻找的简单答案。
I landed here seeking to consume this...
The answer is to split it on the comma and strip the spaces:
To get a list result:
It may not answer the OP's question exactly but might be the simple answer some people are looking for.
这就是我用于列表的内容:
配置文件内容:
代码:
配置内容的字符串
它适用于数字
:
代码:
谢谢。
This is what I use for lists:
config file content:
code :
it work for strings
in case of numbers
config content:
code:
thanks.
因此,我更喜欢的另一种方法是仅拆分值,例如:
可以像这样加载到字符串或整数列表中,如下所示:
此方法可以防止您需要将值括在括号中以作为 JSON 加载。
So another way, which I prefer, is to just split the values, for example:
Could be loaded like this into a list of strings or integers, as follows:
This method prevents you from needing to wrap your values in brackets to load as JSON.
我在项目中完成了类似的任务,其中包含没有值的键的部分:
输出:
app.config:
I completed similar task in my project with section with keys without values:
Output:
app.config:
配置解析器仅支持原始类型进行序列化。 我会使用 JSON 或 YAML 来满足这种要求。
Only primitive types are supported for serialization by config parser. I would use JSON or YAML for that kind of requirement.
要进一步采用 Grr 的答案(我最喜欢的),您可以使用 map 函数,而不是在 .ini 文件中将列表项括在引号中。 这允许您以Python方式指定列表项数据类型。
配置文件:
代码:
输出:
To take Grr's answer (my favorite) a step further, instead of enclosing list items in quotes in the .ini file, you can use the map function. This allows you to pythonically specify list item datatypes.
Config file:
Code:
Output:
如果这是您的 config.ini:
那么使用 configparser 您可以执行以下操作:
您将得到:
split() 方法将返回一个列表,请参阅 Python 字符串文档。
如果您的文件中有空格config.ini 像这样:
那么你最好这样做:
如果你的项目是数字(例如整数),只需应用:
你将得到:
If this is your config.ini:
Then with configparser you could do this:
You will get:
The split()-method will return a list, see Python string docs.
If you have white spaces in your config.ini like this:
Then you'd better do this:
If your items are numbers (integers for instance), just apply:
You will get:
我过去也遇到过同样的问题。 如果您需要更复杂的列表,请考虑通过继承 ConfigParser 创建您自己的解析器。 然后你可以用以下方法覆盖 get 方法:
使用此解决方案,你还可以在配置文件中定义字典。
不过要小心! 这不太安全:这意味着任何人都可以通过您的配置文件运行代码。 如果您的项目中安全性不是问题,我会考虑直接使用 python 类作为配置文件。 以下内容比 ConfigParser 文件更强大且可消耗:
I faced the same problem in the past. If you need more complex lists, consider creating your own parser by inheriting from ConfigParser. Then you would overwrite the get method with that:
With this solution you will also be able to define dictionaries in your config file.
But be careful! This is not as safe: this means anyone could run code through your config file. If security is not an issue in your project, I would consider using directly python classes as config files. The following is much more powerful and expendable than a ConfigParser file:
现在我的 config.cfg 文件可能如下所示:
可以为我的小项目解析为足够细粒度的对象。
这是为了非常快速地解析简单的配置,您将失去获取整数、布尔值和其他类型输出的所有能力,而无需转换从解析器返回的对象,或重新执行由其他地方的 Parser 类。
So now my
config.cfg
file, which could look like this:Can be parsed into fine-grained-enough objects for my small project.
This is for very quick parsing of simple configs, you lose all ability to fetch ints, bools, and other types of output without either transforming the object returned from
Parser
, or re-doing the parsing job accomplished by the Parser class elsewhere.json.loads
&ast.literal_eval
似乎有效,但配置中的简单列表将每个字符视为字节,因此返回甚至方括号....意味着如果配置有
fieldvalue = [1,2,3, 4,5]
然后
config.read(*.cfg)
config['fieldValue'][0]
返回[
代替1
json.loads
&ast.literal_eval
seems to be working but simple list within config is treating each character as byte so returning even square bracket....meaning if config has
fieldvalue = [1,2,3,4,5]
then
config.read(*.cfg)
config['fieldValue'][0]
returning[
in place of1
正如彼得·斯密特(https://stackoverflow.com/a/11866695/7424596)所述
您可能想要扩展 ConfigParser,此外,还可以使用 Interpolator 自动在列表之间进行转换。
作为参考,您可以在底部找到自动转换配置的代码,例如:
因此,如果您请求密钥,您将得到:
代码:
As mentioned by Peter Smit (https://stackoverflow.com/a/11866695/7424596)
You might want to extend ConfigParser, in addition, an Interpolator can be used to automatically convert into and from the list.
For reference at the bottom you can find code which automatically converts config like:
So if you request keys you will get:
Code:
您可以在配置文件中使用列表,然后在 python 中解析它
,也可以在配置文件后面使用 json 文件,如下所示:
you can use list in config file then parse it in python
and also you can use json file behind your config file like this:
split(',') 的改进可能是将逗号分隔值视为 CSV 文件中的记录。
您可以配置方言来解析您喜欢的任何样式的 CSV。
An improvement on split(',') might be to treat the comma separated values as a record in a CSV file
You can configure a dialect to parse whatever style of CSV you like.
[项目]
list = 1,2,3
获取使用:
结果应该是:[1,2,3]
[items]
list = 1,2,3
get using:
Result should be: [1,2,3]
我正在使用 ConfigParser 和 JSON 的组合:
只需阅读它:
如果您的列表很长,您甚至可以换行(感谢@peter-smit):
当然我可以只使用 JSON,但我发现配置文件更具可读性, [DEFAULT] 部分非常方便。
I am using a combination of ConfigParser and JSON:
just read it with:
You can even break lines if your list is long (thanks @peter-smit):
Of course i could just use JSON, but i find config files much more readable, and the [DEFAULT] Section very handy.
没有什么可以阻止您将列表打包到分隔字符串中,然后在从配置中获取字符串后将其解包。 如果您这样做,您的配置部分将如下所示:
它并不漂亮,但对于大多数简单的列表来说它是有效的。
There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like:
It's not pretty but it's functional for most simple lists.
我最近使用列表的配置文件中的专用部分实现了此功能:
并使用 config.items( "paths" ) 来获取路径项的可迭代列表,如下所示:
I recently implemented this with a dedicated section in a config file for a list:
and using
config.items( "paths" )
to get an iterable list of path items, like so:很多人不知道的一件事是允许多行配置值。 例如:
config.get('hello','barlist')
的值现在将是:您可以使用 splitlines 方法轻松分割它(不要忘记过滤空项目)。
如果我们寻找像 Pyramid 这样的大型框架,他们正在使用这种技术:
来源
我自己,如果这对您来说是常见的事情,我可能会扩展 ConfigParser:
请注意,使用此技术时需要注意一些事项
One thing a lot of people don't know is that multi-line configuration-values are allowed. For example:
The value of
config.get('hello','barlist')
will now be:Which you easily can split with the splitlines method (don't forget to filter empty items).
If we look to a big framework like Pyramid they are using this technique:
Source
Myself, I would maybe extend the ConfigParser if this is a common thing for you:
Note that there are a few things to look out for when using this technique
没有提及
转换器
kwarg < code>ConfigParser() 在这些答案中的任何一个都相当令人失望。根据文档,您可以将字典传递给 ConfigParser,这将为解析器和节代理添加一个
get
方法。 因此,对于列表:example.ini
解析器示例:
这是我个人最喜欢的,因为不需要子类化,并且我不必依赖最终用户完美地编写 JSON 或可以由
ast 解释的列表。文字评估。
No mention of the
converters
kwarg forConfigParser()
in any of these answers was rather disappointing.According to the documentation you can pass a dictionary to
ConfigParser
that will add aget
method for both the parser and section proxies. So for a list:example.ini
Parser example:
This is my personal favorite as no subclassing is necessary and I don't have to rely on an end user to perfectly write JSON or a list that can be interpreted by
ast.literal_eval
.