python RawConfigParser從字符串、字典中讀取配置

RawConfigParser讀取配置文件的方法,截止目前爲止還有從字符串、字典中讀取配置文件兩種方法沒有提到。因爲他們的讀取方式類似,所以將他們合在一起來演示兩種方法的使用。
1、配置文件使用之前的mysql.ini文件。

mysql.ini

2、從字符串中讀取配置文件。

import configparser

def main():
   cfg = configparser.RawConfigParser()

   # 如果沒有下面的設置,option將會以小寫輸出
   cfg.optionxform = lambda x: x
   str = u""" 
          [MySQLdb]
         user=script_user
         passWD=user_4_script
         db=jellyfish_user
         host=112.62.16.81
         port=1
         charset=utf8
         maxconnect=5
       """
   cfg.read_string(str)

   print '獲取section節點'
   print cfg.sections()

   print '獲取section的所用配置信息'
   for item in cfg.items('MySQLdb'):
      print item[ 0 ],'\t', item[ 1 ]

有兩個小的地方需要注意一下:

  1. “cfg.optionxform = lambda x: x”,本行代碼保證了打印option時,保持原option的大小寫樣式。
  2. 通過循環讀取節點的配置 “for item in cfg.items(‘MySQLdb’):”。因爲返回數據類型爲元祖,所以只能使用下標打印元祖的內容。

3、從字典中讀取配置。

import configparser

def main():
   dictionary = { 'MySQLdb':{ 'user':'script_user','passwd':'user_4_script','db':'jellyfish_user','host':'112.62.16.81','port':'1'}, 'db':{'1':'true'}}

   cfg = configparser.RawConfigParser()
   cfg.read_dict(dictionary)

   print '獲取section節點'
   print cfg.sections()

   print '獲取section的所用配置信息'
   print cfg.items('MySQLdb')

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章