对于一般的应用场景中配置文件的顺序没有那么的重要,但有些场景中配置文件的顺序是非常有效的,特别是当配置项的值具有覆盖功能时这种问题更加的严重。
以下面的例子为例进行说明:
点击(此处)折叠或打开
- [b]
- y1 = 10
- x2 = 20
- z1 = 30
- [a]
- x2 = 40
- z2 = 10
- y1 = 10
[root@stcell03 test]# python
Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ConfigParser
>>> config = ConfigParser.ConfigParser()
>>> fp = open(r"/root/test/test.conf", "r")
>>> config.readfp(fp)
>>> sections = config.sections()
>>> print sections
['a', 'b']
>>>
具体代码如下所示
点击(此处)折叠或打开
-
import ConfigParser
-
config = ConfigParser.ConfigParser()
-
fp = open(r"/root/test/ceph.conf", "r")
-
config.readfp(fp)
-
sections = config.sections()
- print sections
实际上根据官方的文档可知,可以设置ConfigParser的dict_type参数,改变对应的字典类型,从而解决这种序列问题。
Changed in version 2.6: dict_type was added.
Changed in version 2.7: The default dict_type is collections.OrderedDict. allow_no_value was added.
经过测试在Python 2.7的版本中,配置文件不会出现乱序问题,因此可以在Python 2.6的版本中传递2.7的参数。如下所示:Changed in version 2.7: The default dict_type is collections.OrderedDict. allow_no_value was added.
[root@stcell03 test]# python
Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ConfigParser
>>> from collections import OrderedDict
>>> config = ConfigParser.ConfigParser(dict_type=OrderedDict)
>>> fp = open(r"/root/test/test.conf", "r")
>>> config.readfp(fp)
>>> sections = config.sections()
>>> print sections
['b', 'a']
>>>
具体代码如下:
点击(此处)折叠或打开
-
import ConfigParser
-
from collections import OrderedDict
-
config = ConfigParser.ConfigParser(dict_type=OrderedDict)
-
fp = open(r"/root/test/test.conf", "r")
-
config.readfp(fp)
-
sections = config.sections()
- print sections