分层配置库
stingconf的Python项目详细描述
Stingconf
这是一个通过环境变量,命令行参数, 配置文件和默认值。
安装
pip install stingconf
示例
用
函数定义参数- 示例.py
importstingconfparser=stingconf.Parser('Example module')parser.env_prefix('SC')parser.conf_file('config.yml')parser.add('conf-a',short='a',type=int,default=0)parser.add('conf-b',short='b',type=float,default=0.0)parser.add('conf-c',short='c',type=str,default='conf-c')parser.add('conf-d',short='d',default='conf-d',help='4th config')config=parser.parse()print('CONF_A:',config.CONF_A)print('CONF_B:',config.CONF_B)print('CONF_C:',config.CONF_C)print('CONF_D:',config.CONF_D)
- 配置YML
conf_a:100conf_b:1.0conf_c:file-conf-c
- 运行示例
$ exportSC_CONF_A=300 $ python example.py --conf-a 200 -b 20.0 CONF_A: 300 CONF_B: 20.0 CONF_C: file-conf-c CONF_D: conf-d
使用对象
定义参数- 示例.py
importstingconfdefinitions={'env_prefix':'SC','conf_file':'config.yml','items':{'conf-a':{'arg':{'short':'a'},'type':'int','default':0,},'conf-b':{'arg':{'short':'b'},'type':'float','default':0.0,},'conf-c':{'arg':{'short':'c'},'type':'str','default':'conf-c',},'conf-d':{'arg':{'short':'d'},'default':'conf-d','help':'4th config',},},}parser=stingconf.Parser('Example module',definitions)config=parser.parse()
使用文件
定义参数- definitions.yml
env_prefix:SCconf_file:config.ymlorder:-env-arg-file-defaultitems:user:help:'loginuser'arg:short:upassword:help:'loginpassowrd'arg:short:penable:type:booldefault:falsehelp:'enablesomething'arg:long_prefix:'-'http-proxy:env:no_prefix:trueignorecase:truehttps-proxy:env:no_prefix:trueignorecase:true
- 示例.py
importyamlimportstingconfwithopen('definitions.yml')asf:definitions=yaml.safe_load(f)parser=stingconf.Parser('Example module',definitions)config=parser.parse()
命名约定
环境
环境变量的名称应设置为LIKE_THIS
。
如果需要,可以通过Parser.env_prefix()
设置名称前缀。
参数
应设置参数名like-this
。
如果需要,可以使用短版本参数,方法是将short
传递给Parser.add()
文件
应设置配置文件中变量的名称like_this
目前,支持的格式是json和yaml,内容必须是 非嵌套字典。