使用trafaret和yaml的python配置库
trafaret-config的Python项目详细描述
Status: | Stable |
---|---|
Documentation: | http://trafaret-config.readthedocs.io/ |
这是一个包装器,加载yaml并使用trafaret检查配置,同时 跟踪发生错误的文件的实际行。另外, 它可以很好地打印错误。
基本用法:
importargparseimporttrafaretfromtrafaret_configimportcommandlineTRAFARET=trafaret.Dict({'x':trafaret.String()})defmain():ap=argparse.ArgumentParser()commandline.standard_argparse_options(ap,default_config='config.yaml')## define your command-line arguments here#options=ap.parse_args()config=commandline.config_from_options(options,TRAFARET)pprint.pprint(config)
配置出错时的示例输出(来自 比上面的例子有更好的流量:
bad.yaml:3: smtp.port: value can't be converted to int -> 'unknown' bad.yaml:4: smtp.ssl_port: value can't be converted to int -> 'NaN' bad.yaml:5: port: value can't be converted to int -> '???'
帮助如下:
usage: example.py [-h] [-c CONFIG] [--print-config] [--print-config-vars] [-C] optional arguments: -h, --help show this help message and exit -c CONFIG, --config CONFIG Configuration file (default: 'config.yaml') --print-config Print config as it is read after parsing and exit --print-config-vars Print variables used in configuration file -C, --check-config Check configuration and exit
因为配置中的trafaret config 2.0环境变量被替换 默认情况下,这意味着这样的配置:
url:http://${HOST}:$PORT/
将从环境中插入HOST和PORT变量,如果 变量不存在,将得到以下错误:
config.yaml:2: variable 'PORT' not found -> 'http://${HOST}:$PORT/'
低级接口,不依赖argparse:
importsysimporttrafaretfromtrafaret_configimportConfigError,read_and_validateTRAFARET=trafaret.Dict({'x':trafaret.String()})try:config=read_and_validate('config.yaml',TRAFARET)exceptConfigErrorase:e.output()sys.exit(1)
安装
pip install trafaret-config==2.0.2
许可证
根据
- Apache许可证,2.0版, (./license-apache或http://www.apache.org/licenses/LICENSE-2.0)
- 麻省理工学院许可证(./license-mit或http://opensource.org/licenses/MIT) 由你选择。
贡献
除非您另有明确说明,否则任何出资 按照apache-2.0中的定义,提交以供包含在您的工作中 许可证,应为上述双重许可证,无任何附加条款或 条件。