首頁  >  文章  >  後端開發  >  【Python】ConfigParser模組

【Python】ConfigParser模組

巴扎黑
巴扎黑原創
2016-11-21 15:30:55938瀏覽

一 前言
   最近研究備份還原MySQL資料庫實例,舊的資料配置和新的實例的my.cnf 配置不統一,依賴backup-my.cnf 來判斷innodb_data_file_path 參數是否修改修改。如何解析 my.cnf 呢?於是研究了Python提供ConfigParser模組。此模組可以完成針對常見的設定檔的讀取和修改操作,基本上滿足需求。
二 如何使用
  2.1 設定檔的格式
  設定檔主要由 section區域 構成,section中可以使用option=value或option:value,以設定參數。

[section1 名稱]

option1=值1

....

optionN=值1

.


optionN=值N


  常見的my.cnf 格式如下


[mysqld]

innodb_log_files_in_

innodb_log_block_size = 512

innodb_data_file_path = ibdata1:2G:autoextend

innodb_log_file_size = 536870912

 2.2 ConfigParser 模組

  Python的ConfigParser Module定義了3個類別:RawCnfigParser,ConfigParser,Safefig; ser基於RawCnfigParser做了各自的拓展
本文主要以ConfigParser類為例做介紹。 ConfigParser模組的操作主要包括:

   a 初始化一個ConfigParser實例

   b 讀取設定
   c 修改設定

讀取設定檔常用的方法


.cf.cf.cf. sections()       取得所有的section,並以清單的形式傳回

cf.options(section) 取得指定section下所有option



cf.items(section)  下所有option


cf.items(section)  下所有option


cf.items(section)   的形式回傳


cf.get(section,option) 取得指定section中option的值,傳回為string型別


cf.getint(section,option) 取得指定section中option的值,並傳回為int型別


cf.has_option(section,option) 檢查section下是否有指定的option,有返回True,無返回False 


cf.has_section(section) 檢查是否有section,有返回True,無傳回設定檔常用的方法


cf.add_section(section) 新增一個新的section 


cf.set(section,option,value) 對section中的option進行設定

ecf. section) 刪除指定的section

cf.remove_option(section,option) 刪除指定section中的option 


注意對於修改設定檔的操作呼叫write將內容寫入檔案。

2.3 範例

點擊(此處)折疊或開啟

#!/usr/bin/python2.6


#coding:utf8

歐_hepk
'

new_mycnf_file='my.cnf'


cf =ConfigParser.ConfigParser()

cf.read(new_mycnf_file)

cf.read(new_mycnf_file)
. ,sec


opts = cf.options("mysqld")


print 'options:', opts


kvs =forv.items("myd

    print kv

innodb_data_file_path=cf.get('mysqld','innodb_data_file_path')

innodb_log_file_size=cf.get('mysqld','innodb_log_od_size'))_fffile_od; _path

print 'innodb_log_file_size : ',innodb_log_file_size

print "修改之後"

cf.set('mysqld','innodb_data_file_path','ibdata1:1G:autoextend')

(p.


cf.read(new_mycnf_file)


innodb_data_file_path=cf.get('mysqld','innodb_data_file_path')

yangyi$ python writecnf.py 

sections: ['mysqld']

options: ['innodb_log_files_in_group', 'innodb_page_size', 'innodb_log_block_size',3'innodb_size', 'innodb_log_block_size',31'innodb_datas_odf')o5,50,0005_4,300b_
('innodb_log_files_in_group', '2')


('innodb_page_size', '16384')

('innodb_page_size', '16384')


('innodb_log_block_size', '512')


('innodb_data_I3:, innodb_log_file_size', '536870912' )


('ibdata1', '2g:autoextend = ibdata1:2G:autoextend')

innodb_data_file_path : ibdata1:1G:au來extend

修改後


innodb_data_file_path : ibdata1:1G:autoextend


三小結

   根據ConfigParser 模組提供的函數,基本上可以滿足日常工作中對設定檔的修改操作。其他更詳細的資料請參考官方文件。


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn