Python ConfigParser 模块

ConfigParser 用来解析类似 /etc/my.cnf 这种格式的配置文件,可以对该类型的文件进行增删查改等操作

[root@localhost ~]$ cat /etc/my.cnf     
[mysqld] # [mysqld] 称为 section(段) user    = mysql # key = value 称为 option(选项)
port = 3306
datadir
= /var/lib/mysql socket = /var/lib/mysql/mysql.sock [mysqld_safe] log-error = /var/log/mysqld.log pid-file = /var/run/mysqld/mysqld.pid
In [1]: import ConfigParser

In [2]: c = ConfigParser.ConfigParser()         # 生成一个解析器对象

In [3]: c.read('/etc/my.cnf')                   # 通过对象的read()方法来读取并加载配置文件
Out[3]: ['/etc/my.cnf']

In [4]: c.sections()                            # sections() 用于返回所有section
Out[4]: ['mysqld', 'mysqld_safe']

In [5]: c.has_section('mysqld')                 # has_section() 用于查看是否有指定的section
Out[5]: True

In [6]: c.add_section('mysqldump')              # add_section() 用于添加指定的section,默认追加到末尾

In [7]: c.options('mysqld')                     # options() 用于返回指定section下面的所有option
Out[7]: ['user', 'port', 'datadir', 'socket']

In [8]: c.has_option('mysqld', 'port')          # has_option() 用于查看section下是否有指定的option
Out[8]: True

In [9]: c.get('mysqld', 'port')                 # get() 用于获取section下指定option的值
Out[9]: '3306'

In [10]: c.set('mysqld', 'port', '3310')        # set() 用于修改section下指定option的值,如果该option不存在则会自动创建

In [11]: with open('/tmp/my.cnf', 'w') as fd:   
   ...:     c.write(fd)                         # write() 用于保存修改后的配置,但需要打开并写入到另一个文件      
   ...:   

 

 

 

 

 

 

    

    

posted @ 2019-02-19 22:47  孔雀东南飞  阅读(165)  评论(0编辑  收藏  举报