在一个地方解析文件、环境和其他地方的配置值。
easy-config的Python项目详细描述
下面是使用easy_config的完整工作示例。首先,编写配置类:
# config.pyfromeasy_configimportEasyConfigclassMyProgramConfig(EasyConfig):FILES=['myprogram.ini']NAME='MyProgram'# the name for the .ini file section and the namespace prefix for environment variables# define the options like you would a dataclassnumber:intname:strcheck_bounds:bool=True# options with defaults must all come after non-default options
示例配置文件:
# myprogram.ini[MyProgram]# section name matches `NAME` from the configuration classnumber=3
以及演示用法的示例程序:
# test_config.pyimportsysfromconfigimportMyProgramConfigprint(MyProgramConfig.load(name=sys.argv[1])
使用各种选项运行此程序:
$ python test_config.py Scott MyProgramConfig(number=3, name='Scott', check_bounds=True) $ env MYPROGRAM_CHECK_BOUNDS=False python test_config.py Scott # environment variable names are the all-uppercase transformation of the NAME concatenated with the option name and an underscore MyProgramConfig(number=3, name='Scott', check_bounds=False) $ env MYPROGRAM_NUMBER=10MYPROGRAM_NAME=Charlie python test_config.py Scott MyProgramConfig(number=10, name='Scott', check_bounds=True)
如您所见,值是优先的,参数传递给load覆盖环境中的值,而环境反过来覆盖配置文件中的值。
一旦拥有了MyProgramConfig实例,就可以像使用任何数据类一样使用它。