oslo.config 快速入门!¶
您是 oslo.config 的新手吗?本简短教程将帮助您理解一些基本概念。
先决条件¶
一个纯文本编辑器或支持 Python 的 IDE
一个 Python 解释器
一个可以调用解释器的命令行 shell
oslo_config 库在您的 Python 路径中。
测试脚本¶
将以下内容放入名为 oslocfgtest.py 的文件中。
# The sys module lets you get at the command line arguments.
import sys
# Load up the cfg module, which contains all the classes and methods
# you'll need.
from oslo_config import cfg
# Define an option group
grp = cfg.OptGroup('mygroup')
# Define a couple of options
opts = [cfg.StrOpt('option1'),
cfg.IntOpt('option2', default=42)]
# Register your config group
cfg.CONF.register_group(grp)
# Register your options within the config group
cfg.CONF.register_opts(opts, group=grp)
# Process command line arguments. The arguments tell CONF where to
# find your config file, which it loads and parses to populate itself.
cfg.CONF(sys.argv[1:])
# Now you can access the values from the config file as
# CONF.<group>.<opt>
print("The value of option1 is %s" % cfg.CONF.mygroup.option1)
print("The value of option2 is %d" % cfg.CONF.mygroup.option2)
配置文件¶
将以下内容放入名为 oslocfgtest.conf 的文件中,与 oslocfgtest.py 位于同一目录中。
[mygroup]
option1 = foo
# Comment out option2 to test the default value
# option2 = 123
运行它!¶
从您的命令行 shell 中,在与脚本和配置文件相同的目录中,调用
python oslocfgtest.py --config-file oslocfgtest.conf
享受输出与预期完全一致的喜悦。 如果您一切顺利,您应该会看到
The value of option1 is foo
The value of option2 is 42
现在去尝试更多高级选项设置吧!