4. Python 3中的configparser模块
Python 3中不仅仅是将ConfigParser改名为configparse,还对该模块做了一些改进:
改进1:允许我们以类似字典的方式来操作配置数据
生成一个配置文件:
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'BAR': 'Life',
'BAZ': 'hard'}
config['Section1'] = {}
config['Section1']['an_int'] = '15'
config['Section1']['a_float'] = '3.1415'
config['Section1']['a_bool'] = 'true'
config['Section2'] = {}
config['Section2']['baz'] = 'fun'
config['Section2']['bar'] = 'Python'
config['Section2']['fun'] = '%(bar)s is %(baz)s!'
with open('example.ini', 'w') as configfile:
config.write(configfile)
读取一个已存在的配置文件:
>>> import configparser
>>>
>>> config = configparser.ConfigParser()
>>> config.read('example.ini')
['example.ini']
>>>
>>> config['Section1']['an_int']
'15'
>>> config['Section2']['fun']
'Python is fun!'
改进2:所有的get*()方法都增加了一个fallback参数
Python 2的ConfigParser模块中定义的解析器所提供的get*()方法在获取一个不存在的option的值时会抛出ConfigParser.NoOptionError错误:
>>> import ConfigParser
>>> config = ConfigParser.ConfigParser()
>>> config.read('example.ini')
['example.ini']
>>>
>>> config.options('Section1')
['an_int', 'a_float', 'a_bool', 'bar', 'baz']
>>> config.get('Section1', 'not_exist_option')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\ConfigParser.py", line 618, in get
raise NoOptionError(option, section)
ConfigParser.NoOptionError: No option 'not_exist_option' in section: 'Section1'
>>>
因此,我们需要在获取某个Section下的option时需要先判断该option是否存在,或者需要处理相应的异常信息。而Python 3中的configparser模块提供的所有的get*()方法都增加了一个fallback参数,这个fallback参数可以用于指定获取一个不存在的option的时的默认值,这其实也是类似字典的操作。
需要注意的是: 这个fallback参数必须以关键词参数的形式提供,如果不提供该参数还是会抛出异常(KeyError)。
>>> config = configparser.ConfigParser()
>>> config.read('example.ini')
['example.ini']
>>>
>>> config.options('Section1')
['an_int', 'a_float', 'a_bool', 'bar', 'baz']
>>> config.get('Section1', 'an_int')
'15'
>>> config.get('Section1', 'not_exist_option', fallback='None')
'None'
>>>
改进3:读取配置信息的read*()方法
read()方法新加了一个encoding参数
之前读取配置文件时,都使用open()函数的default encoding,Python 3.2新加了encoding参数允开发者修改打开文件的要使用的字符编码:
read(filenames, encoding=None)
以read_file()方法替代readfp()方法
从Python 3.2开始以read_file()方法替代readp()方法
read_file(f, source=None)
新加了read_string()和read_dict()方法
Python 2中可以使用read()和readfp()方法很方便的从文件中读取配置信息,如果要从一个字符串中读取配置信息,需要这样做:config.readfp(io.BytesIO(str_config_data)) ,上面有例子。且Python 2中没有提供从一个Python字典读取配置数据的方法。
Python 3中专门提供了read_string()和read_dict()方法来分别从字符串和Python字典中读取配置数据:
read_string(string, source='<string>')
read_dict(dictionary, source='<dict>')
改进4:write()方法新加了一个space_around_delimiter参数
Python 3中的write()方法新加了一个space_around_delimiter参数,用于写入文件的配置数据的option的key和option之间的分隔符前后是否保留空白字符。该参数默认值为True,则文件格式是这样的:
[DEFAULT]
bar = Life
baz = hard
...
如果该参数值为False,则文件格式是这样的:
[DEFAULT]
bar=Life
baz=hard
...
改进5:解析器类的构造函数增加了很多灵活的参数
class configparser.ConfigParser(defaults=None, dict_type=collections.OrderedDict,
allow_no_value=False, delimiters=('=', ':'),
comment_prefixes=('#', ';'), inline_comment_prefixes=None,
strict=True, empty_lines_in_values=True,
default_section=configparser.DEFAULTSECT,
interpolation=BasicInterpolation(), converters={})
class configparser.RawConfigParser(defaults=None, dict_type=collections.OrderedDict,
allow_no_value=False, *, delimiters=('=', ':'),
comment_prefixs=('#', ';'), inline_comment_prefixes=None,
strict=True, empty_lines_in_values=True,
default_section=configparser.DEFAULTSECT[, interpolation])
四、总结
本文对Python中的XML数据和应用配置文件的处理模块进行了尽可能详细的介绍并附带了一些示例代码。本文主要是对之前那篇<的一个补充,但是在实际开发工作中也经常会用到这些内容,希望对大家有所帮助。
本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-05/144327.htm
