Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ConfigParser 寫配置檔時的亂序問題與解法

編輯:關於 Android 開發

ConfigParser 寫配置檔時的亂序問題與解法

在 CentOS 6.5 環境下,通常使用 ConfigParser 來解析配置檔,而 CentOS 6.5 的 Python 版本為 2.6.6。

對於一般應用場景,配置檔的順序並沒有那麼重要;但在某些場景中,順序卻至關關鍵——尤其是當配置項的值存在覆蓋關係時,亂序問題會變得格外嚴重。

以下面這個例子說明:

  1. [b]
  2. y1 = 10
  3. x2 = 20
  4. z1 = 30
  5. [a]
  6. x2 = 40
  7. z2 = 10
  8. y1 = 10

在 CentOS 6.5 中常用的解析寫法如下:

[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
...
>>> import ConfigParser
>>> config = ConfigParser.ConfigParser()
>>> fp = open(r"/root/test/test.conf", "r")
>>> config.readfp(fp)
>>> sections = config.sections()
>>> print sections
['a', 'b']

完整程式碼如下:

  1. import ConfigParser
  2. config = ConfigParser.ConfigParser()
  3. fp = open(r"/root/test/ceph.conf", "r")
  4. config.readfp(fp)
  5. sections = config.sections()
  6. print sections

從輸出可以看到,配置檔中 section 的原始順序是 b、a,實際讀出的卻是 a、b。一般場景下或許無所謂,但在包含覆蓋關係的場景中問題就暴露了:比如 b 是通用配置,a 是特殊配置,a 需要覆蓋 b 中的某些配置項,此時順序錯亂就會導致結果錯誤。

根本原因在於 ConfigParser 默認使用 dict 保存解析到的資料,而 dict 本身是無序的(按鍵值組織),因此出現了 a、b 顛倒的情況。

實際上根據官方文檔,可以透過設置 dict_type 參數來改變字典型別,從而解決這個問題(dict_type 自 2.6 版加入;2.7 版起默認即為 collections.OrderedDict)。經測試,在 Python 2.7 中不會出現亂序,因此我們可以在 2.6 環境中手動傳入 2.7 的參數:

[root@stcell03 test]# python
...
>>> 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']

對應的完整程式碼:

  1. import ConfigParser
  2. from collections import OrderedDict
  3. config = ConfigParser.ConfigParser(dict_type=OrderedDict)
  4. fp = open(r"/root/test/test.conf", "r")
  5. config.readfp(fp)
  6. sections = config.sections()
  7. print sections

這樣一來,section 的順序便與原檔保持一致,覆蓋類配置的正確性也就得到了保障。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved