Python模块学习

配置文件

  很多软件都用到了配置文件,像git运行的时候会读取~/gitconfig,MySQL运行的时候会读取/etc/my.cnf,Python 提供的包管理工具pip命令,也会去读取~/.pip/pip.cnf文件。

  配置文件的好处是,配置成功后不需要每次使用时都指定相应的参数,而且,典型的ini格式的配置文件具有和编程语言无关、可读性强和易于处理等优点、已经被广泛使用。

  一个典型的配置文件包含一到多个章节(section),每个章节下包含一到多个选项(option)。下面是一个MySQL的配置文件:

[client]
port = 3306
user = mysql
password = mysql
host = 127.0.0.1

[mysqld]
basedir = /usr/local/mysql
datadir = /usr/local/mysql/data
tmpdir = /tmp
skip-external-locking

ConfigParser模块

  Python中使用ConfigParser模块来解析配置文件。ConfigParser中包含一个ConfigParser类,一个ConfigParser对象可以同时解析多个配置文件,一般情况下我们只会使用ConfigParser模块解析一个文件文件。

  首先,解析一个配置文件,需要先创建一个ConfigParser对象,创建ConfigParser对象时有多个参数,其中比较重要的是allow_no_value,allow_no_value默认取值为False,表示在配置文件中是否允许有没有选项的值的情况。默认情况下每个选项都应该有一个值,但是在一些特殊的应用选项下,选项存在即为真,不存在即为假,比如上面MySQL的配置文件skip-external-locking。所以如果需要解析这样的参数,那么就需要在实例化的时候添加allow_no_value 为True

>>> import ConfigParser
>>> cp = ConfigParser.ConfigParser(allow_no_value=True)
>>> 

  有了ConfigParser对象以后,我们就可以使用read方法,从配置文件中读取配置内容了。

>>> cp.read('/etc/my.cnf')
['/etc/my.cnf']
>>> 

主要方法

ConfigParser对象中有很多方法,其中与读取配置文件,判断配置相关的方法有:

  • sections:返回一个包含所有章节的列表
  • has_sections:判断章节是否存在
  • items:以元祖的形式返回所有的选项
  • options:返回一个包含章节下所有选项的列表
  • has_option:判读某个选项是否存在
  • get、getboolean、getinit、getfloat:获取选项的值

下面以MySQL的配置文件my.cnf为例子

>>> cp.sections()
['mysqld', 'mysqld_safe']

>>> cp.has_section('mysqld')
True

>>> cp.has_section('client')
False

>>> cp.options('mysqld')
['datadir', 'socket', 'user', 'symbolic-links']

>>> cp.has_option('mysqld','user') 
True

>>> cp.get('mysqld','user')
'mysql'
>>> 

ConfigParser对象也提供了许多方法便于我们修改配置文件:

  • remove_section:删除一个章节
  • add_section:添加一个章节
  • remote_option:删除一个选项
  • set:添加一个选项
  • write:将ConfigParser对象中保存的数据保存的文件中去
>>> cp.add_section('client')
>>> cp.set('client','host','127.0.0.1')
>>> cp.set('client','user','mysql')
>>> cp.set('client','password','123456')
>>> cp.write(open('/tmp/my.cnf','w'))
>>> exit()
[root@centos-linux python]# cd /tmp
my.cnf 

[root@centos-linux tmp]# cat my.cnf 
[mysqld]
datadir = /var/lib/mysql
socket = /var/lib/mysql/mysql.sock
user = mysql
symbolic-links = 0

[mysqld_safe]
log-error = /var/log/mysqld.log
pid-file = /var/run/mysqld/mysqld.pid

[client]
host = 127.0.0.1
user = mysql
password = 123456

[root@centos-linux tmp]# 

  

原文地址:https://www.cnblogs.com/dachenzi/p/7968076.html