一 前言
最近研究備份恢複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=值N
[section2 名稱]
option1=值1
....
optionN=值N
常見的 my.cnf 格式 如下
[mysqld]
innodb_log_files_in_group = 2
innodb_page_size = 16384
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,SafeConfigParser. 其中RawCnfigParser 是最基礎的設定檔讀取類,ConfigParser、SafeConfigParser基於 RawCnfigParser做了各自的拓展
本文主要以ConfigParser類為例做介紹。ConfigParser模組的操作主要包括:
a 初始化一個 ConfigParser執行個體
b 讀取配置
c 修改配置
讀取設定檔常用的方法
cf.read(filename) 讀取設定檔內容
cf.sections() 擷取所有的section,並以列表的形式返回
cf.options(section) 擷取指定section下所有option
cf.items(section) 擷取指定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,無返回 False
修改設定檔常用的方法
cf.add_section(section) 向設定檔中添加一個新的section
cf.set(section,option,value) 對section中的option進行設定
cf.remove_section(section) 刪除指定的section
cf.remove_option(section,option) 刪除指定section中的option
注意對於修改設定檔的操作需要調用write將內容寫入設定檔。
2.3 例子
點擊(此處)摺疊或開啟
#!/usr/bin/python2.6
#coding:utf8
import ConfigParser
old_mycnf_file='backup-my.cnf'
new_mycnf_file='my.cnf'
cf =ConfigParser.ConfigParser()
cf.read(new_mycnf_file)
sec=cf.sections()
print 'sections:' ,sec
opts = cf.options("mysqld")
print 'options:', opts
kvs = cf.items("mysqld")
for kv in kvs:
print kv
innodb_data_file_path=cf.get('mysqld','innodb_data_file_path')
innodb_log_file_size=cf.get('mysqld','innodb_log_file_size')
print 'innodb_data_file_path :',innodb_data_file_path
print 'innodb_log_file_size :',innodb_log_file_size
print "修改之後"
cf.set('mysqld','innodb_data_file_path','ibdata1:1G:autoextend')
cf.write(open(new_mycnf_file, "w"))
cf.read(new_mycnf_file)
innodb_data_file_path=cf.get('mysqld','innodb_data_file_path')
print 'innodb_data_file_path :',innodb_data_file_path
yangyiDBA:test yangyi$ python writecnf.py
sections: ['mysqld']
options: ['innodb_log_files_in_group', 'innodb_page_size', 'innodb_log_block_size', 'innodb_data_file_path', 'innodb_log_file_size', 'ibdata1']
('innodb_log_files_in_group', '2')
('innodb_page_size', '16384')
('innodb_log_block_size', '512')
('innodb_data_file_path', 'ibdata1:2G:autoextend')
('innodb_log_file_size', '536870912')
('ibdata1', '2g:autoextend = ibdata1:2G:autoextend')
innodb_data_file_path : ibdata1:1G:autoextend
innodb_log_file_size : 536870912
修改之後
innodb_data_file_path : ibdata1:1G:autoextend
三 小結
根據ConfigParser 模組提供的函數,基本可以滿足日常工作中對設定檔的修改操作。其他更詳細的資料請參考官方文檔。