# demo.ini [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
上面的demo.ini是一个很是基础的配置文件,它由多个部分(section)组成,每部分包含了带值的选项。ConfigParse类的实例能够对其进行读写操做。python
建立配置文件:app
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {"ServerAliveInterval": "45", "Compression": "yes", "CompressionLevel": "9", "ForwardX11": "yes"} config["bitbucket.org"] = {} config["bitbucket.org"]["User"] = "hg" config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret["Port"] = "50022" topsecret["ForwardX11"] = "no" with open("demo.ini", "w") as configfile: config.write(configfile)
对配置解析器的处理与字典相似。函数
读取配置文件:this
>>> config = configparser.ConfigParser() >>> config.sections() [] >>> config.read("demo.ini") ["demo.ini"] >>> config.sections() ['bitbucket.org', 'topsecret.server.com'] >>> "bitbucket.org" in config True >>> "bitbong.com" in config False >>> config["bitbucket.org"]["User"] "hg" >>> config['DEFAULT']['Compression'] "yes" >>> topsecret = config['topsecret.server.com'] >>> topsecret['ForwardX11'] "no" >>> for key in config["bitbucket.org"]: ... print(key) user serveraliveinterval compression compressionlevel forwardx11 >>> config["bitbucket.org"]["ForwardX11"] "yes"
注意点:[DEFAULT]为其余全部section提供默认值,section中的全部键大小写不敏感并以小写字母存储spa
配置解析器老是存储配置的值为字符串类型,所以用户须要按需转换为指望的数据类型。因为这种需求很是广泛,配置解析器提供了一系列更简便的方法来处理整数(getint()
)、浮点数(getfloat()
)及布尔值(getboolean()
)。用户也能够自行注册转换器或定制配置解析器已提供的转换器。3d
>>> topsecret.getboolean('ForwardX11') False >>> config['bitbucket.org'].getboolean('ForwardX11') True >>> config.getboolean('bitbucket.org', 'Compression') True
注意点:getboolean()
方法对大小写不敏感,能识别'yes'/'no', 'on'/'off', 'true'/'false'和'1'/'0'为对应的布尔值代理
和字典同样,可使用section的get()
方法提供后备值:code
>>> topsecret.get('CompressionLevel') '9' >>> topsecret.get('Cipher') >>> topsecret.get('Cipher', '3des-cbc') '3des-cbc
须要注意的是,默认值的优先级高于后备值。好比要想在'topsecret.server.com'中获取'CompressionLevel'的值,即便指定了后备值,仍然获得的是'DEFAULT'中的值:orm
>>> topsecret.get('CompressionLevel', '3') '9'
此外,除了section的get()
方法,还提供了解析器级别的get()
方法,支持向后兼容,后备值经过fallback
关键字指定:server
>>> config.get("bitbucket.org", "monster", fallback="No such things as monsters") "No such things as monsters"
fallback
关键字一样支持在getint()
, getfloat()
和getboolean()
中使用
[section_name]
的形式打头,后跟以特定字符(默认是=
或:
)分隔的键值对。#
和;
为前缀。应该避免注解与键或值处在同一行,由于这将致使把注解视为值的一部分。[Simple Values] key=value spaces in keys=allowed spaces in values=allowed as well spaces around the delimiter = obviously you can also use : to delimit keys from values [All Values Are Strings] values like this: 1000000 or this: 3.14159265359 are they treated as numbers? : no integers, floats and booleans are held as: strings can use the API to get converted values directly: true [Multiline Values] chorus: I'm a lumberjack, and I'm okay I sleep all night and I work all day [No Values] key_without_value empty string value here = [You can use comments] # like this ; or this # By default only in an empty line. # Inline comments can be harmful because they prevent users # from using the delimiting characters as parts of values. # That being said, this can be customized. [Sections Can Be Indented] can_values_be_as_well = True does_that_mean_anything_special = False purpose = formatting for readability multiline_values = are handled just fine as long as they are indented deeper than the first line of a value # Did I mention we can indent comments, too?
ConfigParser支持插值,调用get()
方法返回值以前将对值进行预处理
默认使用的Interpolation类。容许值包含格式化字符串,该字符串引用同一section中的值或DEFAULTSECT
section中的值。其余默认值能够在初始化时提供。
[Paths] home_dir: /Users my_dir: %(home_dir)s/lumberjack my_pictures: %(my_dir)s/Pictures
在上面的例子中,interpolation设置为BasicInterpolation()
的ConfigParser将解析%(home_dir)s
为home_dir
的值,%(my_dir)s
将解析为/Users/lumberjack
。引用链中使用的键不须要在配置文件中以任何特定的顺序指定。
若是interpolation设置为None
,将直接返回%(home_dir)s/lumberjack
做为my_dir
的值。
扩展的Interpolation类,实现了更高级的语法。它使用${section:option}
表示来自外部section的值,若是省去了section:
,默认指当前section(以及可能的DEFAULTSECT
section的值)
[Common] home_dir: /Users library_dir: /Library system_dir: /System macports_dir: /opt/local [Frameworks] Python: 3.2 path: ${Common:system_dir}/Library/Frameworks/ [Arthur] nickname: Two Sheds last_name: Jackson my_dir: ${Common:home_dir}/twosheds my_pictures: ${my_dir}/Pictures python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
映射协议访问是容许像操做字典同样使用自定义对象的功能的通用名称。在configparser中,映射接口经过parser["section"]["option"]
的形式实现。
parser["section"]
返回解析器中section的值的代理,值从原始解析器中获取但并不是经过复制的方式。在section代理上改变值的操做,其实是对原始解析器的改变。
configparser对象虽然表现的尽量接近字典,但仍有一些区别须要注意:
for option in parser["section"]
语句生成的option名称老是被optionxform
函数转换为小写。拥有"a"选项的section经过如下两种方式访问都将返回True:"a" in parser["section"] "A" in parser["section"]
DEFAULTSECT
的值,也就是说,对section的.clear()
操做可能并无真正的清空,这是由于没法从该section删除默认值。在除DEFAULTSECT
之外的section上删除默认值(前提是没有对默认值重写)将抛出KeyError
异常>>> del topsecret["forwardx11"] >>> topsecret["forwardx11"] 'yes' >>> del topsecret["serveraliveinterval"] Traceback (most recent call last): ... raise KeyError(key) KeyError: 'serveraliveinterval'
DEFAULTSECT
不能从解析器移除
ValueError
异常parser.clear()
操做对它没有任何影响parser.popitem()
不会返回DEFAULTSECT
>>> del config["DEFAULT"] Traceback (most recent call last): ... raise ValueError("Cannot remove the default section.") ValueError: Cannot remove the default section. >>> config.clear() >>> config["DEFAULT"]["serveraliveinterval"] '45'
parser.get(section, option, **kwargs)
- 第二个参数并不是字典的get()
方法表示的后备值,但section级别的get()
方法与映射协议倒是兼容的parser.items(raw=False, vars=None)
兼容映射协议(返回包含DEFAULTSECT
的(section_name, section_proxy)对的列表)。另有指定section的调用方式:parser.items(section, raw=False, vars=None)
.后者返回指定section的(option, value)对的列表,raw参数指定value中的格式化字符串是否插值表示>>> list(config.items()) [('DEFAULT', <Section: DEFAULT>), ('bitbucket.org', <Section: bitbucket.org>), ('topsecret.server.com', <Section: topsecret.server.com>)] >>> list(config.items("bitbucket.org")) [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
省略
省略
class configparser.ConfigParser(defaults=None, dict_type=dict, 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={})
defaults()
返回包含实例范围默认值的字典
sections()
返回可用section的名称列表(不包含默认section的名称)
add_section(section)
添加section。若是该section已经存在,抛出DuplicateSectionError
异常;若是传入的是默认section的名称,抛出ValueError
异常;若是传入的参数不是字符串类型,抛出TypeError
异常
has_section(section)
判断section是否存在。默认section老是返回False
options(section)
返回指定section的可用选项列表(包含DEFAULTSECT
中的选项)。指定默认section将抛出NoSectionError
异常
has_option(section, option)
若是section存在且包含指定的option,返回True,不然返回False。若是传递的section为None
或""
,视为默认section
read(filenames, encoding=None)
读取并解析可迭代的文件名,返回成功解析的文件名列表
若是filenames是一个字符串,或字节对象又或者是类路径对象,视其为单个文件。若是filenames中的某个文件不能打开,该文件将被忽略
若是filenames中全部文件都不存在,ConfigParser实例将包含空数据集。若是某个应用须要导入初始化值,应该在调用read()导入可选配置文件前调用read_file()
读取相应的初始化配置文件,由于read_file()
读取不能打开的文件时会抛出FileNotFoundError
异常,而不会直接忽略
import configparser, os config = configparser.ConfigParser() config.read_file(open('defaults.cfg')) config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], encoding='cp1250')
read_file(f, source=None)
从可迭代生成Unicode字符串的f(例如以文本模式打开的文件对象)读取及解析配置数据
read_string(string, source='<string>')
从字符串中解析配置数据
read_dict(dictionary, source='<dict>')
从提供相似dict的items()方法的对象加载配置。key是section名称,value是包含选项和值的字典。若是使用的字典类型支持保留顺序,section及其选项将按序添加,全部值自动转换为字符串
get(section, option, * , raw=False, vars=None[, fallback])
获取指定section的选项的值。vars参数做为字典对象传递。option按照vars,section,DEFAULTSECT的顺序进行查找,若是不存在且提供了fallback参数,返回fallback的值,fallback能够是None
raw参数指定value中的格式化字符串是否插值表示,与option的查找顺序相同
getint(section, option, * , raw=False, vars=None[, fallback])
转换option的值为int类型
getfloat(section, option, * , raw=False, vars=None[, fallback])
转换option的值为float类型
getboolean(section, option, * , raw=False, vars=None[, fallback])
转换option的值为bool类型
items(raw=False, vars=None)
items(section, raw=False, vars=None)
前者返回包含DEFAULTSECT
的(section_name, section_proxy)对的列表。后者返回指定section的(option, value)对的列表
set(section, option, value)
若是section存在,设置option的值为value,不然抛出NoSectionError
异常。option和value必须是字符串类型,不然抛出TypeError
异常
write(fileobject, space_around_delimiters=True)
将ConfigParser对象写入以文件模式打开的文件。
remove_option(section, option)
从section中移除指定的选项。若是section不存在,抛出NoSectionError
异常。若是option存在返回True,不然返回False
remove_section(section)
移除指定section。若是section存在返回True,不然返回False(对默认section的操做老是返回False)
optionxform(option)
对option的处理函数,默认返回option的小写形式。能够经过继承重写或设置ConfigParser实例的optionxform
属性(接收一个字符串参数并返回一个新的字符串的函数)改变默认行为。
cfgparser = ConfigParser() cfgparser.optionxform = str
读取配置文件时,option两边的空格在调用此函数前先被移除
readfp(fp, filename=None)
已弃用,使用 read_file()
替代
configparser.MAX_INTERPOLATION_DEPTH
当raw参数为false时,get()方法递归插值的最大深度。仅在使用默认的BasicInterpolation
时才有意义
省略
省略