简体   繁体   English

如何使用configobj定义和选择值组?

[英]How to define and select groups of values using configobj?

I would like to define several groups of values where the values of a particular group are used if that group is selected. 我想定义几组值,如果选择了某个组,则使用该组的值。

Here's a an example to make that clearer: 这是一个使这一点更清楚的示例:

[environment]
type=prod

[prod]
folder=data/
debug=False

[dev]
folder=dev_data/
debug=True

Then to use it: 然后使用它:

print config['folder'] # prints 'data/' because config['environment']=='prod'

Is there a natural or idiomatic way to do this in configobj or otherwise? 是否有自然或惯用的方式在configobj或其他方式中执行此操作?


Additional Info 附加信息

My current thoughts are overwriting or adding to the resulting config object using some logic post parsing the config file. 我当前的想法是使用一些解析配置文件的逻辑来覆盖或添加到生成的配置对象中。 However, this feels contrary to the nature of a config file, and feels like it would require somewhat complex logic to validate. 但是,这感觉与配置文件的性质背道而驰,并且感觉需要进行一些复杂的逻辑验证。

I know this is maybe not exactly what you're searching for, but have you considered using json for easy nested access? 我知道这可能不完全是您要搜索的内容,但是您是否考虑过使用json进行简单的嵌套访问?

For example, if your config file looks like 例如,如果您的配置文件看起来像

{
    "environment": {
        "type": "prod"
    },
    "[dev]": {
        "debug": "True",
        "folder": "dev_data/"
    },
    "[prod]": {
        "debug": "False",
        "folder": "data/"
    }
}

you can access it with [dev] or [prod] key to get your folder: 您可以使用[dev][prod]键访问它以获取文件夹:

>>> config = json.loads(config_data)
>>> config['[dev]']['folder']
'dev_data/'
>>> config['[prod]']['folder']
'data/'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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