| 1 |
========================== |
| 2 |
oslo.config Quick Start! |
| 3 |
========================== |
| 4 |
|
| 5 |
Are you brand new to oslo.config? This brief tutorial will get you started |
| 6 |
understanding some of the fundamentals. |
| 7 |
|
| 8 |
Prerequisites |
| 9 |
------------- |
| 10 |
* A plain text editor or Python-enabled IDE |
| 11 |
* A Python interpreter |
| 12 |
* A command shell from which the interpreter can be invoked |
| 13 |
* The oslo_config library in your Python path. |
| 14 |
|
| 15 |
Test Script |
| 16 |
----------- |
| 17 |
Put this in a file called ``oslocfgtest.py``. |
| 18 |
|
| 19 |
.. code:: python |
| 20 |
|
| 21 |
# The sys module lets you get at the command line arguments. |
| 22 |
import sys |
| 23 |
|
| 24 |
# Load up the cfg module, which contains all the classes and methods |
| 25 |
# you'll need. |
| 26 |
from oslo_config import cfg |
| 27 |
|
| 28 |
# Define an option group |
| 29 |
grp = cfg.OptGroup('mygroup') |
| 30 |
|
| 31 |
# Define a couple of options |
| 32 |
opts = [cfg.StrOpt('option1'), |
| 33 |
cfg.IntOpt('option2', default=42)] |
| 34 |
|
| 35 |
# Register your config group |
| 36 |
cfg.CONF.register_group(grp) |
| 37 |
|
| 38 |
# Register your options within the config group |
| 39 |
cfg.CONF.register_opts(opts, group=grp) |
| 40 |
|
| 41 |
# Process command line arguments. The arguments tell CONF where to |
| 42 |
# find your config file, which it loads and parses to populate itself. |
| 43 |
cfg.CONF(sys.argv[1:]) |
| 44 |
|
| 45 |
# Now you can access the values from the config file as |
| 46 |
# CONF.<group>.<opt> |
| 47 |
print("The value of option1 is %s" % cfg.CONF.mygroup.option1) |
| 48 |
print("The value of option2 is %d" % cfg.CONF.mygroup.option2) |
| 49 |
|
| 50 |
Conf File |
| 51 |
--------- |
| 52 |
Put this in a file called ``oslocfgtest.conf`` in the same directory as |
| 53 |
``oslocfgtest.py``. |
| 54 |
|
| 55 |
.. code:: ini |
| 56 |
|
| 57 |
[mygroup] |
| 58 |
option1 = foo |
| 59 |
# Comment out option2 to test the default value |
| 60 |
# option2 = 123 |
| 61 |
|
| 62 |
Run It! |
| 63 |
------- |
| 64 |
From your command shell, in the same directory as your script and conf, invoke: |
| 65 |
|
| 66 |
.. code:: shell |
| 67 |
|
| 68 |
python oslocfgtest.py --config-file oslocfgtest.conf |
| 69 |
|
| 70 |
Revel in the output being exactly as expected. If you've done everything |
| 71 |
right, you should see: |
| 72 |
|
| 73 |
.. code:: shell |
| 74 |
|
| 75 |
The value of option1 is foo |
| 76 |
The value of option2 is 42 |
| 77 |
|
| 78 |
Now go play with some more advanced option settings! |