企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
这个模块是python标准库模块,从2.6.6开始引入,用来解析配置文件。 ## 直接使用 #### 实例化 ``` import ConfigParser config_obj = ConfigParser.ConfigParser() ``` --- #### 读取配置文件 ``` # 读取文件对象 config_obj.readfp(fo) # 读取文件 config_obj.read() ``` #### 写配置文件,文件对象 ``` config_obj.write(fo) ``` --- #### 判断option是否存在 ``` config_obj.has_section(section) ``` #### 获取sections ``` config_obj.sections() ``` #### 添加section ``` config_obj.add_section ``` #### 移除section ``` config_obj.remove_section(section) ``` --- #### 判断option是否存在 ``` config_obj.has_option(section, option) ``` #### 获取options ``` config_obj.options(section) ``` #### 获取值 ``` config_obj.get(section, option) ``` #### 获取(key/value) tuple ``` config_obj.items(section) ``` #### 添加option ``` config_obj.set(section, option, value=None) ``` #### 删除option ``` config_obj.remove_option(section, option) ``` --- ## 定制类 ``` #!/usr/bin/env python # encoding: utf-8 from ConfigParser import ConfigParser class MysqlConfig(ConfigParser): def __init__(self, config_file, **kwargs): ConfigParser.__init__(self, allow_no_value=True) # super(MysqlConfig, self).__init__(allow_no_value=True) self.config_file = config_file self.kwargs = kwargs # 初始化时就执行读取配置文件操作 self.read(self.config_file) self.set_vars(self.kwargs) self.get_vars('mysqld') def set_vars(self, kwargs): "设置类属性" for k, v in kwargs.items(): setattr(self, k, v) def get_vars(self, section='mysqld'): """读取配置文件的参数存为类属性,默认是mysqld""" attr_dict = {} options = self.options(section) for item in options: attr_dict[item] = self.get(section, item) self.set_vars(attr_dict) # def get_vars(self, section='mysqld'): # attr_dict = dict(self.items(section)) # self.set_vars(attr_dict) if __name__ == '__main__': conf_obj = MysqlConfig('/usr/share/doc/mysql-server-5.1.73/my-huge.cnf') print conf_obj.items('mysqld') ```