彩虹然

rainbow-ran

python3.7之configparser配置文件分析器

configparser模块提供ConfigParser实现基本配置语言的类,该基本配置语言提供的结构类似于Microsoft Windows INI文件中的结构。

我们来看一个非常基本的配置文件,如下所示:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

该文件由多个部分组成,每个部分都包含带有值的键。 configparser类可以读取和写入此类文件。

创建配置文件

以编程方式创建上述配置文件:

import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
    config.write(configfile)

读配置文件的基本用法

1.创建实例:config = configparser.ConfigParser();

2.查看每个部分的标题,即[section]:config.sections();

3.查看每个部分的键-值对:我们可以像对待字典一样对待配置解析器,但有一些差异;

4.DEFAULT部分为所有其他部分提供了默认值。

代码如下:

import configparser
config = configparser.ConfigParser()
print(config.sections())
# []
print(config.read('example.ini'))
# ['example.ini']
print(config.sections())
# ['bitbucket.org', 'topsecret.server.com']
print('bitbucket.org' in config)
# True
print('bytebong.com' in config)
# False
print(config['bitbucket.org']['User'])
# 'hg'
print(config['DEFAULT']['Compression'])
# 'yes'
topsecret = config['topsecret.server.com']
print(topsecret['ForwardX11'])
# 'no'
print(topsecret['Port'])
# '50022'
for key in config['bitbucket.org']:  
    print(key)
# user
# compressionlevel
# serveraliveinterval
# compression
# forwardx11
print(config['bitbucket.org']['ForwardX11'])
# 'yes'

支持的数据类型

配置解析器不会猜测配置文件中值的数据类型,而是始终将它们内部存储为字符串。这意味着,如果需要其他数据类型,则应自行转换:

>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0

由于此任务非常常见,因此配置解析器提供了一系列方便的getter方法来处理整数,浮点数和布尔值。最后一个是最有趣的,因为仅将值传递给bool()就没有好处,因为bool('False')它仍然存在True。这就是配置解析器还提供的原因getboolean()。

例如:

>>> topsecret.getboolean('ForwardX11')
False
>>> config['bitbucket.org'].getboolean('ForwardX11')
True
>>> config.getboolean('bitbucket.org', 'Compression')
True

除了之外getboolean(),config解析器还提供了等价getint()和 getfloat()方法。您可以注册自己的转换器并自定义提供的转换器。

INI文件结构

配置文件由多个部分组成,每个部分都由一个[section]标题开头,然后是由特定字符串(=或:)分隔的键/值条目。默认情况下,节名称区分大小写,但键不是。前导和尾随空格从键和值中删除。值可以省略,在这种情况下,键/值定界符也可以省去。值也可以跨多行,只要它们缩进的深度比值的第一行深。根据解析器的模式,空白行可能被视为多行值的一部分或被忽略。

配置文件可能包括注释,由特定字符(前缀#和;)。注释可能会自己出现在否则为空的行上,可能会缩进。

例如:

[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?

官方文档:https://docs.python.org/3/library/configparser.html#id14

posted @ 2020-03-26 10:54  彩虹然  阅读(610)  评论(0)    收藏  举报