day5-configparser模塊


一、概述

在軟件開發過程中,很多時候需要處理配置文件的讀取解析和改寫,在python中專門處理配置文件的模塊就是configpaser了。顧名思義,configpaser就是配置解析器,可用來對符合格式規范的.conf,ini等配置文件進行解析讀取,並支持增刪改查、定義新的配置文件等處理。

二、配置文件格式規范

可以被configpaser處理的配置文件需符合以下格式規范:

  1 [mysqld]
  2 datadir=/var/lib/mysql
  3 socket=/var/lib/mysql/mysql.sock
  4 user=mysql
  5 # Disabling symbolic-links is recommended to prevent assorted security risks
  6 symbolic-links=0
  7 character-set-server=utf8
  8 
  9 [mysqld_safe]
 10 log-error=/var/log/mysqld.log
 11 pid-file=/var/run/mysqld/mysqld.pid
 12 
 13 [client]
 14 default-character-set=utf8
 15 
 16 [mysql]
 17 default-character-set=utf8
細心的同學可發現這就是mysql的默認配置文件,類似的還有ansible的hosts文件:
  1 [group1]
  2 host1 var1=value1 var2=value2
  3 host2 var3=value2
  4 [group2]
  5 host3
  6 [group1:children]
  7 group2

三、configpaser的常見用法

前文提到,configpaser支持對配置文件的解析讀取、增刪改查和定義新的配置文件等處理,可滿足不同場景下對配置文件的處理需求,下面我們先來創建一個示例配置文件,然后逐一詳述讀取和增刪改查用法。

3.1 創建配置文件

創建示例配置文件

  1 import configparser
  2 
  3 config = configparser.ConfigParser()
  4 #開始創建第一個section,類似於list賦值方式,值為dict
  5 config['DEFAULT'] = {'compressionlevel': '9',
  6                      'serveraliveinterval': '45',
  7                       'compression': 'yes'}
  8 config['DEFAULT']['forwardx11'] = 'yes'
  9 #創建第二個section
 10 config['bitbucket.org'] = {}
 11 #類似於通過list的下標來賦值元素
 12 config['bitbucket.org']['user'] = 'hg'
 13 config['topsecret.server.com'] = {}
 14 #通過中間變量來替代
 15 topsecret = config['topsecret.server.com']
 16 topsecret['host port'] = '50022'
 17 topsecret['forwardx11'] = 'no'
 18 #開始寫入配置文件
 19 with open('test.conf', 'w', encoding='utf-8') as configfile:
 20     config.write(configfile)

注意:
創建的key-value中里面如果有數字,需要加引號變成string形式,否則會報數據類型錯誤。

創建的配置文件顯示如下:

  1 [DEFALUT]
  2 compressionlevel = 9
  3 serveraliveinterval = 45
  4 compression = yes
  5 forwardx11 = yes
  6 
  7 [bitbucket.org]
  8 user = hg
  9 
 10 [topsecret.server.com]
 11 host port = 50022
 12 forwardx11 = no

3.2 讀取配置文件

很多場景下我們更多的是需要解析讀取其他軟件的配置文件,以獲取相關的參數信息。

  • 讀取section
    section即符合格式規范的配置文件的一級目錄,方括號[]包含的部分.sections()方法用於獲取配置文件的除default外的所有section,以list形式返回
      1 >>> import configparser
      2 >>> config = configparser.ConfigParser()
      3 >>> config.sections()  #獲取section
      4 []
      5 >>> config.read('test.conf') #讀取配置文件
      6 ['test.conf']
      7 >>> config.sections() #成功返回section,但不包括default
      8 ['bitbucket.org', 'topsecret.server.com']
      9 >>> config.defaults() #返回default section的鍵值對
     10 OrderedDict([('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compres
     11 sion', 'yes'), ('forwardx11', 'yes')])
  • 判斷section是否存在
      1 >>> 'bitbucket.org' in config
      2 True
      3 >>> 'bitbucket.org1' in config
      4 False
      5 >>> 'DEFAULT' in config
      6 True
      7 >>>
  • 讀取section內的值
    獲取某個key對應的value可以以類似於list下標的形式獲取,options()方法可獲取指定section和default在內的所有key,items可獲取指定section和default在內的所有key-value對
      1 >>> config.options('bitbucket.org')
      2 ['user', 'compressionlevel', 'serveraliveinterval', 'compression', 'forwardx11']
      3 >>> config.items('bitbucket.org')
      4 [('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compression', 'yes'),('forwardx11', 'yes'), ('user', 'hg')]
      5 >>> config['bitbucket.org']['user']
      6 'hg'
      7 >>>
  • 循環獲取section內的key值
    可以通過config[‘section_name’]的方式循環獲取,也可以通過options方法循環獲取
      1 >>> for key in config['bitbucket.org']:
      2 ...     print(key)
      3 ...
      4 user
      5 compressionlevel
      6 serveraliveinterval
      7 compression
      8 forwardx11
      9 >>>
     10 
     11 >>> for key in config.options('bitbucket.org'):
     12 ...     print(key)
     13 ...
     14 user
     15 compressionlevel
     16 serveraliveinterval
     17 compression
     18 forwardx11

3.3 configpaser的增刪改查

  • 讀取
    主要的讀取方法如下:
  • -read(filename)               直接讀取文件內容
    -sections()                      得到所有的section,並以列表的形式返回
    -options(section)             得到該section的所有option
    -items(section)                得到該section的所有鍵值對
    -get(section,option)         得到section中option的值,返回為string類型
    -getint(section,option)      得到section中option的值,返回為int類型,還有相應的getboolean()和getfloat() 函數。

      1 import configparser
      2 
      3 config = configparser.ConfigParser()
      4 config.read('test.conf')
      5 
      6 print(config.sections())
      7 print(config.options('topsecret.server.com'))
      8 print(config.items('topsecret.server.com'))
      9 print(config.get('topsecret.server.com', 'host port'))
     10 print(type(config.get('topsecret.server.com', 'host port')))
     11 print(config.getint('topsecret.server.com', 'host port'))
     12 print(type(config.getint('topsecret.server.com', 'host port')))
     13 
     14 
     15 程序輸出:
     16 ['bitbucket.org', 'topsecret.server.com']
     17 ['host port', 'forwardx11', 'compressionlevel', 'serveraliveinterval', 'compression']
     18 [('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compression', 'yes'), ('forwardx11', 'no'), ('host port', '50022')]
     19 50022
     20 <class 'str'>
     21 50022
     22 <class 'int'>
    注意:
    default是一個特殊的全局section,我們獲取section時不會返回它,但是當我們在獲取其他section的key或者key-value對時,會包括default相應的內容,可以認為它是一個全局缺省的section把。

  • 更改
    通過set方式可實現對已有key-value的修改,如果set的對象不存在,則報錯該section不存在
      1 import configparser
      2 
      3 config = configparser.ConfigParser()
      4 config.read('test.conf')
      5 
      6 print(config.get('topsecret.server.com', 'host port'))
      7 config.set('topsecret.server.com', 'host port' ,'60022')
      8 print(config.get('topsecret.server.com', 'host port'))
      9 
     10 結果輸出:
     11 50022
     12 60022


  • 增加
    新增section:
      1 >>> import configparser
      2 >>> config = configparser.ConfigParser()
      3 >>> config.read('test.conf')
      4 ['test.conf']
      5 >>> config.has_section('topsecret.server.com')
      6 True
      7 >>> config.has_section('sync_data') #判斷是否有該section
      8 False
      9 >>> config.options('topsecret.server.com')
     10 ['host port', 'forwardx11', 'compressionlevel', 'serveraliveinterval', 'compress
     11 ion']
     12 >>> config.add_section('sync_data') #新增section
     13 >>> config.sections() #新增成功
     14 ['bitbucket.org', 'topsecret.server.com', 'sync_data']
  • 新增option:
    set還有一種用法是為一個存在的section新增option:
      1 import configparser
      2 
      3 config = configparser.ConfigParser()
      4 config.read('test.conf')
      5 
      6 print(config.options('topsecret.server.com'))
      7 #新增option autoreload
      8 config.set('topsecret.server.com', 'autoreload' ,'yes')
      9 print(config.options('topsecret.server.com'))
     10 print(config.items('topsecret.server.com'))
     11 
     12 程序輸出:
     13 ['host port', 'forwardx11', 'compressionlevel', 'serveraliveinterval', 'compression']
     14 ['host port', 'forwardx11', 'autoreload', 'compressionlevel', 'serveraliveinterval', 'compression']
     15 [('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compression', 'yes'), ('forwardx11', 'no'), ('host port', '50022'), ('autoreload', 'yes')]
     16 #新增option后可以看到多出autoreload,items也能返回它對應的value
    


  • 刪除

      1 >>> import configparser
      2 >>> config = configparser.ConfigParser()
      3 >>> config.read('test.conf')
      4 ['test.conf']
      5 >>> config.sections()
      6 ['bitbucket.org', 'topsecret.server.com']
      7 
      8 #開始刪除section
      9 >>> config.remove_section('bitbucket.org')
     10 True
     11 >>> config.sections()
     12 ['topsecret.server.com'] #成功刪除section
     13 
     14 >>> config.options('topsecret.server.com')
     15 ['host port', 'forwardx11', 'compressionlevel', 'serveraliveinterval', 'com
     16 ion']
     17 #開始刪除option
     18 >>> config.remove_option('topsecret.server.com','host port')
     19 True
     20 >>> config.options('topsecret.server.com')
     21 ['forwardx11', 'compressionlevel', 'serveraliveinterval', 'compression'] #成功刪除option
     22 
     23 #刪除默認的default的option失敗
     24 >>> config.remove_option('topsecret.server.com','compression')
     25 False
     26 >>> config.options('topsecret.server.com')
     27 ['forwardx11', 'compressionlevel', 'serveraliveinterval', 'compression']

      注意:如果要刪除default的全局默認option,必須指定section為default后才能刪除 

  1 >>> config.remove_option('DEFAULT','compression')
  2 True
  3 >>> config.options('topsecret.server.com')
  4 ['forwardx11', 'compressionlevel', 'serveraliveinterval']

  • 持久化保存
    上述增、刪、改的操作都只是處理了內存中的對象,並沒有進行持久化保存,會面臨一個重新read后修改又被回滾的問題,這時切記修改完了要立即進行持久化保存處理。保存方法與操作普通文件非常類似:
      1 >>> import configparser
      2 >>> config = configparser.ConfigParser()
      3 >>> config.read('test.conf')
      4 >>> with open('test.conf','w',encoding='utf-8') as configfile:
      5 ...     config.write(configfile)
      6 ...
      7 >>> config.read('test.conf')
      8 ['test.conf']
      9 #持久化保存后重新讀取,此前的修改已經生效
     10 >>> config.sections()
     11 ['topsecret.server.com']
     12 >>> config.options('topsecret.server.com')
     13 ['forwardx11', 'compressionlevel', 'serveraliveinterval']

      持久化保存時可指定保存到源文件進行覆蓋寫處理,也可以另存為其他文件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM