ConfigParser寫設定檔亂序問題_PHP教程

來源:互聯網
上載者:User

ConfigParser寫設定檔亂序問題


在Centos6.5的環境下,通常使用ConfigParser進行設定檔的解析。Centos6.5的Python版本為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
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']
>>>
具體代碼如下所示
 
  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,而實際輸出的section為a, b。對於一般情境下無所謂,但在包含的情境中,比如b是一個通用的配置,而a是一個特殊的配置,a的配置能夠覆蓋b中某些配置項的內容,此時就會出現問題。出現這種問題的根本原因是在ConfigParser中預設採用了dict儲存解析到的資料,而dict本身是無序的,實際上是根據索引值的順序儲存,因此出現了a,b的順序。這樣也就可能導致設定檔的亂序。

實際上根據官方的文檔可知,可以設定ConfigParser的dict_type參數,改變對應的字典類型,從而解決這種序列問題。Changedinversion2.6:dict_typewasadded.
Changedinversion2.7:Thedefaultdict_typeiscollections.OrderedDict.allow_no_valuewasadded.經過測試在Python 2.7的版本中,設定檔不會出現亂序問題,因此可以在Python 2.6的版本中傳遞2.7的參數。如下所示:
[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']
>>>
具體代碼如下:
 
  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


http://www.bkjia.com/PHPjc/1108024.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1108024.htmlTechArticleConfigParser寫設定檔亂序問題 在Centos6.5的環境下,通常使用ConfigParser進行設定檔的解析。Centos6.5的Python版本為Python 2.6.6。 對於一般的應...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.