usage: example4.py [-h] [--config-dir DIR] [--config-file PATH] [--debug]
[--nodebug] [--noverbose] [--verbose] [--version]
optional arguments:
-h, --help show this help message and exit
--config-dir DIR Path to a config directory to pull *.conf files from.
This file set is sorted, so as to provide a predictable
parse order if individual options are over-ridden. The
set is parsed after the file(s) specified via previous
--config-file, arguments hence over-ridden options in
the directory take precedence.
--config-file PATH Path to a config file to use. Multiple config files can
be specified, with values in later files taking
precedence. The default files used are: None.
--debug, -d Print debugging output.
--nodebug The inverse of --debug
--noverbose The inverse of --verbose
--verbose, -v Print more verbose output.
--version show program's version number and exit
#!/usr/bin/env python
# encoding: utf-8
#定义了一个名为rabbit的组,记住组的名字也非常重要,后面会用到
rabbit_group = cfg.OptGroup(name='rabbit',
title='RabbitMQ options')
#定义了两个选项,和上文中说到的定义选项没有不论什么差别
rabbit_host_opt = cfg.StrOpt('host',
default='localhost',
help='IP/hostname to listen on.'),
rabbit_port_opt = cfg.PortOpt('port',
default=5672,
help='Port number to listen on.')
def register_rabbit_opts(conf):
#通过CONF类来注冊了一个组。(CONF类啥都要先注冊后使用。注冊事实上就是在CONF类内部做解析呢)
conf.register_group(rabbit_group)
# options can be registered under a group in either of these ways:
#注冊选项的时候通过指定组来把选项加入到特定的组中,指定组能够有例如以下两种方式,一种就是直接使用OptGroup实例的方式
#第二种就是使用配置组的名字这里是rabbit
conf.register_opt(rabbit_host_opt, group=rabbit_group)
conf.register_opt(rabbit_port_opt, group='rabbit')
#没提供group就是默认组DEFAULT
之前仅仅有默认组的时候。在命令行使用–debug就会自己主动去DEFAULT组去找,那么如今加入了一个rabbit组,假设要找rabbit组中的host该怎么通过命令行来指定呢这也是非常方便的直接通过前缀来推断比如–rabbit-host指的就是rabbit组中的host选项。
配置文件句不多说了,定义一个[rabbit]就能够了,怎样在代码中訪问呢,也非常easy。直接使用conf.rabbit.host就能够了。 Special Handling Instructions
说了这么多,是不是感觉cfg Module有点强大,我也这么认为的,这个部分介绍下cfg Module关于选项提供的一些处理指令吧.