在 CentOS 6.5 (Python 2.6.6) 環境下使用 ConfigParser 解析配置文件時,常遇到 section 順序被字母排序的問題。例如原始文件順序為 [b] 後接 [a],但 config.sections() 卻返回 ['a', 'b']。這在配置項具有覆蓋關係時會導致嚴重錯誤——通用配置被特定配置錯誤覆蓋。
ConfigParser 內部默認使用無序字典 dict 存儲數據,導致解析順序丟失。Python 2.7 起默認改用 collections.OrderedDict,但 2.6 需手動指定。
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'] 保持原始順序
設置 dict_type=OrderedDict 後,sections() 正確返回原始文件順序 ['b', 'a'],確保配置覆蓋邏輯按預期生效。這對於多環境配置繼承、基礎配置與覆蓋配置分離等場景至關重要。
注意:Python 3 已內建有序字典,
configparser(注意小寫) 默認保持順序,無需額外配置。