简介
ConfigParser
模块在python3中修改为configparser
.这个模块定义了一个ConfigParser类,该类的作用是使用配置文件生效,配置文件的格式和windows的INI文件的格式相同
该模块的作用 就是使用模块中的RawConfigParser()
、ConfigParser()
、 SafeConfigParser()
这三个方法(三者择其一),创建一个对象使用对象的方法对指定的配置文件做增删改查 操作。
配置文件有不同的片段组成和Linux中repo文件中的格式类似:
格式:
<span style="color:#000000"><code>[section]
name=<span style="color:#000088">value</span>
或者
name: <span style="color:#000088">value</span>
<span style="color:#009900">"#"</span> 和<span style="color:#009900">";"</span> 表示注释
[DEFAULT] <span style="color:#009900">#设置默认的变量值,初始化</span></code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
<span style="color:#000000"><code>[My Section]
foodir: %(dir)s/whatever
dir=frob
<span style="color:#000088">long</span>: <span style="color:#000088">this</span> <span style="color:#000088">value</span> continues
<span style="color:#000088">in</span> the next line
</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
%(dir)s
会被frob
代替。默认值会以字典的形式传递给ConfigParser的构造器。section一般存放的哦内置目录下,如果切换到其他的目录需啊哟指定存放位置。
方法
下面这三种方式使用时,切记注意
在调用这三个函数时,切记这三个函数会将调用optionxform()
,在传递键值对数据时,会将键名 全部转化为小写。
RawConfigParser()
<span style="color:#000000"><code>ConfigParser.RawConfigParser([defaults[, dict_type[, allow_no_value]]])
defaults : 如果指定默认值,则使用默认值的键值对
dict_type:使用新的section的键值对
allow_no_value :默认是<span style="color:#000088">False</span>,如果是<span style="color:#000088">True</span>,表示可以接收空值(<span style="color:#000088">None</span>)
<span style="color:#000088">return</span>:对象</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
不支持可变参数,在section中不能存在%()s
ConfigParser()
<span style="color:#000000"><code>ConfigParser.ConfigParser([defaults[, dict_<span style="color:#4f4f4f">type</span>[, allow_no_value]]]) </code></span>
- 1
在default中必须出现%()s
SafeConfigParser()
<span style="color:#000000"><code> ConfigParser.SafeConfigParser([defaults[, dict_<span style="color:#4f4f4f">type</span>[, allow_no_value]]]) </code></span>
- 1
更加智能化,在section中是否存在%()s
会自动判断
传递参数使用函数optionxform(),foo %(bar)s 和 foo %(BAR)s是相同的,optionxform()会将大写字母全部转换为小写。
常见异常
异常 | 描述 |
---|---|
ConfigParser.Error | 所有异常的基类 |
ConfigParser.NoSectionError | 指定的section没有找到 |
ConfigParser.DuplicateSectionError | 调用add_section() 时,section名称已经被使用 |
ConfigParser.NoOptionError | 指定的参数没有找到 |
ConfigParser.InterpolationError | 当执行字符串插值时出现问题时,出现异常的基类 |
ConfigParser.InterpolationDepthError | 当字符串插值无法完成时,因为迭代次数超过了最大的范围,所以无法完成。InterpolationError的子类 |
InterpolationMissingOptionError | 当引用的选项不存在时,会出现异常。InterpolationError的子类 |
ConfigParser.InterpolationSyntaxError | 当产生替换的源文本不符合所需的语法时,就会出现异常。InterpolationError的子类。 |
ConfigParser.MissingSectionHeaderError | 当试图解析一个没有分段标题的文件时,会出现异常。 |
ConfigParser.ParsingError | 当试图解析文件时发生错误时,会出现异常 |
ConfigParser.MAX_INTERPOLATION_DEPTH | 当raw参数为false时,get()的递归插值的最大深度。这只适用于ConfigParser类 |
RawConfigParser 对象
对象的操作可以分为两大类,一种是对配置文件的操作,另一种是对读取后数据流的操作。
对配置文件的操作
读取配置文件
方法 | 描述 |
---|---|
read(filenames) | filesnames是一个列表,需要从文件加载初始值的应用程序应该在调用read()之前使用readfp()加载所需的文件或文件。 |
readfp(fp[, filename]) | 在fp中,从文件或文件类对象中读取和解析配置数据(只使用readline()方法)。如果文件名被省略,并且fp有一个name属性,它被用于文件名;默认值为< ? >。 |
写入配置文件
方法 | 描述 |
---|---|
write(fileobject) | 将配置的表示写入指定的文件对象。这个表示可以由未来的read()调用解析。 |
对内存中数据流的操作
增加配置文件中的值
方法 | 描述 |
---|---|
add_section(section) | 向实例添加一个section |
删除配置文件中的值
方法 | 描述 |
---|---|
remove_option(section, option) | 从指定的部分中删除指定的选项。如果该部分不存在,请提出NoSectionError。如果存在的选项被删除,返回True;否则返回False。 |
remove_section(section) | 从配置中删除指定的section。如果这个部分确实存在,返回True。否则返回假 |
修改配置文件中的值
方法 | 描述 |
---|---|
set(section, option, value) | 如果给定的部分存在,将给定的选项设置为指定的值 |
optionxform(option) | 也可以在一个实例上重新设置它,对于一个需要字符串参数的函数。例如,将其设置为str,将使选项名称区分大小写 |
查找配置文件中的值
方法 | 描述 |
---|---|
defaults() | 返回包含实例范围默认值的字典。 |
sections() | 返回可用的section的列表;默认section不包括在列表中 |
has_section(section) | 指示指定的section是否出现在配置中。默认的section未被确认 |
options(section) | 返回指定section中可用的选项列表。 |
has_option(section, option) | 如果给定的section存在,并且包含给定的选项,则返回True;否则返回False |
get(section, option) | 为指定的section获取一个选项值。 |
getint(section, option) | 它将指定section中的选项强制转换为整数 |
getfloat(section, option) | 它将指定section中的选项强制转换为浮点型 |
getboolean(section, option) | 强制转换为布尔型,”1”, “yes”, “true”, and “on”, 转换为True,”0”, “no”, “false”, and “off”, 转换为Falseo 其他返回ValueError. |
items(section) | 返回给定section中每个选项的(name,value)对的列表。 |
<span style="color:#000000"><code>import ConfigParser, <span style="color:#4f4f4f">os</span>
config = ConfigParser.ConfigParser()
config.readfp(open(<span style="color:#009900">'defaults.cfg'</span>))
config.read([<span style="color:#009900">'site.cfg'</span>, <span style="color:#4f4f4f">os</span>.path.expanduser(<span style="color:#009900">'~/.myapp.cfg'</span>)])
</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
<span style="color:#000000"><code>cfgparser = ConfigParser()
<span style="color:#000088">...</span>
cfgparser.optionxform = str
</code></span>
- 1
- 2
- 3
- 4
ConfigParser对象
SafeConfigParser中包含ConfigParser相同的方法,还有一部分增加的方法
方法 | 描述 |
---|---|
get(section, option[, raw[, vars]]) | 为指定的section获取一个选项值。如果提供了vars,它必须是一个字典。该选项在vars(如果提供)、分段和默认值中查找, |
items(section[, raw[, vars]]) | 返回给定section中每个选项的(名称、值)对的列表 |
所有的“%”插值都在返回值中展开,除非原始的参数是真的。内插键的值与选项相同
SafeConfigParser对象
set(section, option, value)
如果给定的部分存在,将给定的选项设置为指定的值;否则提高NoSectionError。值必须是字符串(str或unicode);如果没有,则会出现类型错误
实例
实例一:写配置文件
<span style="color:#000000"><code>import ConfigParser
config = ConfigParser.RawConfigParser()
# When adding sections <span style="color:#000088">or</span> items, <span style="color:#000088">add</span> them <span style="color:#000088">in</span> the <span style="color:#000088">reverse</span> <span style="color:#000088">order</span> <span style="color:#000088">of</span>
# how you want them <span style="color:#000088">to</span> be displayed <span style="color:#000088">in</span> the actual file.
# <span style="color:#000088">In</span> addition, please note that <span style="color:#000088">using</span> RawConfigParser<span style="color:#009900">'s and the raw
# mode of ConfigParser'</span>s respective <span style="color:#000088">set</span> functions, you can assign
# non-string values <span style="color:#000088">to</span> keys internally, but will receive an error
# when attempting <span style="color:#000088">to</span> <span style="color:#000088">write</span> <span style="color:#000088">to</span> a file <span style="color:#000088">or</span> when you get it <span style="color:#000088">in</span> non-raw
# mode. SafeConfigParser does <span style="color:#000088">not</span> allow such assignments <span style="color:#000088">to</span> <span style="color:#000088">take</span> place.
config.add_section(<span style="color:#009900">'Section1'</span>)
config.<span style="color:#000088">set</span>(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'an_int'</span>, <span style="color:#009900">'15'</span>)
config.<span style="color:#000088">set</span>(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'a_bool'</span>, <span style="color:#009900">'true'</span>)
config.<span style="color:#000088">set</span>(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'a_float'</span>, <span style="color:#009900">'3.1415'</span>)
config.<span style="color:#000088">set</span>(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'baz'</span>, <span style="color:#009900">'fun'</span>)
config.<span style="color:#000088">set</span>(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'bar'</span>, <span style="color:#009900">'Python'</span>)
config.<span style="color:#000088">set</span>(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'foo'</span>, <span style="color:#009900">'%(bar)s is %(baz)s!'</span>)
# Writing our configuration file <span style="color:#000088">to</span> <span style="color:#009900">'example.cfg'</span>
<span style="color:#000088">with</span> open(<span style="color:#009900">'example.cfg'</span>, <span style="color:#009900">'wb'</span>) <span style="color:#000088">as</span> configfile:
config.<span style="color:#000088">write</span>(configfile)
</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
实例二:读配置文件
<span style="color:#000000"><code>import ConfigParser
config = ConfigParser.RawConfigParser()
config.<span style="color:#000088">read</span>(<span style="color:#009900">'example.cfg'</span>)
# getfloat() <span style="color:#000088">raises</span> an exception <span style="color:#000088">if</span> the value <span style="color:#000088">is</span> <span style="color:#000088">not</span> a float
# getint() <span style="color:#000088">and</span> getboolean() also <span style="color:#000088">do</span> this <span style="color:#000088">for</span> their respective types
a_float = config.getfloat(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'a_float'</span>)
an_int = config.getint(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'an_int'</span>)
print a_float + an_int
# Notice that the next output does <span style="color:#000088">not</span> interpolate <span style="color:#009900">'%(bar)s'</span> <span style="color:#000088">or</span> <span style="color:#009900">'%(baz)s'</span>.
# This <span style="color:#000088">is</span> because we are <span style="color:#000088">using</span> a RawConfigParser().
<span style="color:#000088">if</span> config.getboolean(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'a_bool'</span>):
print config.get(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'foo'</span>)
</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
实例三:获取插入值
<span style="color:#000000"><code>import ConfigParser
config = ConfigParser.ConfigParser()
config.read('example.cfg')
# <span style="color:#000088">Set</span> the third, optional argument <span style="color:#000088">of</span> <span style="color:#000088">get</span> <span style="color:#000088">to</span> <span style="color:#006666">1</span> <span style="color:#000088">if</span> you wish <span style="color:#000088">to</span> use raw mode.
print config.<span style="color:#000088">get</span>(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'foo'</span>, <span style="color:#006666">0</span>) # -> <span style="color:#009900">"Python is fun!"</span>
print config.<span style="color:#000088">get</span>(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'foo'</span>, <span style="color:#006666">1</span>) # -> <span style="color:#009900">"%(bar)s is %(baz)s!"</span>
# The optional fourth argument <span style="color:#000088">is</span> a dict <span style="color:#000088">with</span> members that will take
# precedence <span style="color:#000088">in</span> interpolation.
print config.<span style="color:#000088">get</span>(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'foo'</span>, <span style="color:#006666">0</span>, {<span style="color:#009900">'bar'</span>: <span style="color:#009900">'Documentation'</span>,
<span style="color:#009900">'baz'</span>: <span style="color:#009900">'evil'</span>})
</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
实例四:默认值
所有三种类型的config分析器都可以使用默认值。如果在其他地方没有定义一个选项,那么它们就被用于插值
<span style="color:#000000"><code>import ConfigParser
# New instance with <span style="color:#009900">'bar'</span> <span style="color:#000088">and</span> <span style="color:#009900">'baz'</span> defaulting to <span style="color:#009900">'Life'</span> <span style="color:#000088">and</span> <span style="color:#009900">'hard'</span> each
config = ConfigParser.SafeConfigParser({<span style="color:#009900">'bar'</span>: <span style="color:#009900">'Life'</span>, <span style="color:#009900">'baz'</span>: <span style="color:#009900">'hard'</span>})
config.read(<span style="color:#009900">'example.cfg'</span>)
<span style="color:#4f4f4f">print</span> config.get(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'foo'</span>) # -> <span style="color:#009900">"Python is fun!"</span>
config.remove_option(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'bar'</span>)
config.remove_option(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'baz'</span>)
<span style="color:#4f4f4f">print</span> config.get(<span style="color:#009900">'Section1'</span>, <span style="color:#009900">'foo'</span>) # -> <span style="color:#009900">"Life is hard!"</span>
</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
实例五:在各section之间移动选项
<span style="color:#000000"><code><span style="color:#000088">def</span> <span style="color:#009900">opt_move</span><span style="color:#4f4f4f">(config, section1, section2, option)</span>:
<span style="color:#000088">try</span>:
config.set(section2, option, config.get(section1, option, <span style="color:#006666">1</span>))
<span style="color:#000088">except</span> ConfigParser.NoSectionError:
<span style="color:#880000"># Create non-existent section</span>
config.add_section(section2)
opt_move(config, section1, section2, option)
<span style="color:#000088">else</span>:
config.remove_option(section1, option)
</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
实例六:配置文件中有空值
一些配置文件包含了没有值的设置,但是它与ConfigParser支持的语法相一致。对构造函数的不允许值参数可以被用来表示应该接受这样的值
<span style="color:#000000"><code><span style="color:#006666">>>> </span><span style="color:#000088">import</span> ConfigParser
<span style="color:#006666">>>> </span><span style="color:#000088">import</span> io
<span style="color:#006666">>>> </span>sample_config = <span style="color:#009900">"""
<span style="color:#006666">... </span>[mysqld]
<span style="color:#006666">... </span>user = mysql
<span style="color:#006666">... </span>pid-file = /var/run/mysqld/mysqld.pid
<span style="color:#006666">... </span>skip-external-locking
<span style="color:#006666">... </span>old_passwords = 1
<span style="color:#006666">... </span>skip-bdb
<span style="color:#006666">... </span>skip-innodb
<span style="color:#006666">... </span>"""</span>
<span style="color:#006666">>>> </span>config = ConfigParser.RawConfigParser(allow_no_value=<span style="color:#000088">True</span>)
<span style="color:#006666">>>> </span>config.readfp(io.BytesIO(sample_config))
<span style="color:#006666">>>> </span><span style="color:#880000"># Settings with values are treated as before:</span>
<span style="color:#006666">>>> </span>config.get(<span style="color:#009900">"mysqld"</span>, <span style="color:#009900">"user"</span>)
<span style="color:#009900">'mysql'</span>
<span style="color:#006666">>>> </span><span style="color:#880000"># Settings without values provide None:</span>
<span style="color:#006666">>>> </span>config.get(<span style="color:#009900">"mysqld"</span>, <span style="color:#009900">"skip-bdb"</span>)
<span style="color:#006666">>>> </span><span style="color:#880000"># Settings which aren't specified still raise an error:</span>
<span style="color:#006666">>>> </span>config.get(<span style="color:#009900">"mysqld"</span>, <span style="color:#009900">"does-not-exist"</span>)
Traceback (most recent call last):
...
ConfigParser.NoOptionError: No option <span style="color:#009900">'does-not-exist'</span> <span style="color:#000088">in</span> section: <span style="color:#009900">'mysqld'</span></code></span>