ConfigParser: disordered configuration file writing
In Centos6.5, ConfigParser is usually used to parse the configuration file. The Python version of Centos6.5 is Python 2.6.6.
The configuration file sequence is not so important in general application scenarios, but in some scenarios, the configuration file sequence is very effective, this problem is especially serious when the value of a configuration item has the overwriting function.
The following example is used to describe:
- [b]
- y1 = 10
- x2 = 20
- z1 = 30
- [a]
- x2 = 40
- z2 = 10
- y1 = 10
Common Configuration File Parsing methods in Centos 6.5 are as follows:
[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. conf", "r ")
>>> Config. readfp (fp)
>>> Sections = config. sections ()
>>> Print sections
['A', 'B']
>>>
The Code is as follows:
- import ConfigParser
- config = ConfigParser.ConfigParser()
- fp = open(r"/root/test/ceph.conf", "r")
- config.readfp(fp)
- sections = config.sections()
- print sections
According to the above output, the section sequence of the configuration file is B, a, and the actual output section is a, B. It doesn't matter in general scenarios, but in included scenarios, for example, B is a general configuration, while a is a special configuration, the configuration of a can overwrite the content of some configuration items in B. In this case, a problem occurs. The root cause of this problem is that in ConfigParser, dict is used by default to save the parsed data, and dict itself is unordered. In fact, it is saved in the order of key values, therefore, the order of a and B appears. This may lead to disordered configuration files.
According to the official documentation, you can set the dict_type parameter of ConfigParser to change the corresponding dictionary type to solve this sequence problem. Changedinversion2.6: dict_typewasadded.
Changedinversion2.7: thedefadicdict_typeiscollections.ordereddict.allow_no_valuewasadded. As follows:
[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. conf", "r ")
>>> Config. readfp (fp)
>>> Sections = config. sections ()
>>> Print sections
['B', 'a']
>>>
The Code is as follows:
- 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