相关疑难解决方法(0)

使用Python中的设置文件的最佳做法是什么?

我有一个命令行脚本,我运行了很多参数.我现在已经到了一个我有太多参数的地方,我想也有一些字典形式的参数.

因此,为了简化操作,我希望使用设置文件来运行脚本.我真的不知道用什么库来解析文件.这样做的最佳做法是什么?我当然可以自己敲一些东西,但是如果有一些库,那我就是耳朵.

一些"要求":

  • 而不是使用pickle我希望它是一个可以轻松阅读和编辑的直接文本文件.
  • 我希望能够在其中添加类似字典的数据,即应该支持某种形式的嵌套.

一个简化的伪示例文件:

truck:
    color: blue
    brand: ford
city: new york
cabriolet:
    color: black
    engine:
        cylinders: 8
        placement: mid
    doors: 2
Run Code Online (Sandbox Code Playgroud)

python settings configuration parsing yaml

308
推荐指数
4
解决办法
24万
查看次数

Python:使用"点符号"访问YAML值

我正在使用YAML配置文件.所以这是在Python中加载我的配置的代码:

import os
import yaml
with open('./config.yml') as file:
    config = yaml.safe_load(file)
Run Code Online (Sandbox Code Playgroud)

此代码实际上创建了一个字典.现在的问题是,为了访问值,我需要使用大量的括号.

YAML:

mysql:
    user:
        pass: secret
Run Code Online (Sandbox Code Playgroud)

蟒蛇:

import os
import yaml
with open('./config.yml') as file:
    config = yaml.safe_load(file)
print(config['mysql']['user']['pass']) # <--
Run Code Online (Sandbox Code Playgroud)

我更喜欢这样的东西(点符号):

config('mysql.user.pass')
Run Code Online (Sandbox Code Playgroud)

所以,我的想法是利用PyStache render()接口.

import os
import yaml
with open('./config.yml') as file:
    config = yaml.safe_load(file)

import pystache
def get_config_value( yml_path, config ):
    return pystache.render('{{' + yml_path + '}}', config)

get_config_value('mysql.user.pass', config)
Run Code Online (Sandbox Code Playgroud)

这会是一个"好"的解决方案吗?如果没有,什么是更好的选择?

附加问题[已解决]

我决定使用IljaEverilä的解决方案.但现在我还有一个问题:你如何在DotConf周围创建一个包装器Config类?

以下代码不起作用,但我希望您了解我正在尝试做的事情:

class Config( DotDict ):
    def __init__( self ):
        with open('./config.yml') as file: …
Run Code Online (Sandbox Code Playgroud)

python yaml python-3.x

9
推荐指数
1
解决办法
5543
查看次数

标签 统计

python ×2

yaml ×2

configuration ×1

parsing ×1

python-3.x ×1

settings ×1