以下内容/示例均来自python官方文档,有兴趣的同学可以去查看原文档。
解析INI文件结构
如官网提供的示例 example.ini
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
1. 创建config对象
import configparser
config = configparser.ConfigParser()
2. config读取配置
- 方法1:从文件名读取配置
config.read(file_path)
In [5]: config.read('example.ini')
Out[5]: ['example.ini']
In [6]: config.sections()
Out[6]: ['bitbucket.org', 'topsecret.server.com']
- 方法2:从文件对象读取配置
read_file(f_obj, source=None)
f 为文件对象,从 f 读取并解析配置数据,
可选参数 source 指定要读取的文件名称。 如果未给出并且 f 具有 name 属性,则该属性会被用作 source;默认值为 '<???>'。
In [8]: config.read_file(open("example.ini"), source=None)
In [9]: config.sections()
Out[9]: ['bitbucket.org', 'topsecret.server.com']
- 方法3:从字符串读取配置
read_string(string, source='<string>')
In [12]: sample_config = """
...: [DEFAULT]
...: ServerAliveInterval = 45
...: Compression = yes
...: CompressionLevel = 9
...: ForwardX11 = yes
...:
...: [bitbucket.org]
...: User = hg
...:
...: [topsecret.server.com]
...: Port = 50022
...: ForwardX11 = no
...: """
In [13]: sample_config
Out[13]: '\n[DEFAULT]\nServerAliveInterval = 45\nCompression = yes\nCompressionLevel = 9\nForwardX11 = yes\n\n[bitbucket.org]\nUser = hg\n\n[topsecret.server.com]\nPort = 50022\nForwardX11 = no\n'
In [14]: config.read_string(sample_config)
In [15]: config.sections()
Out[15]: ['bitbucket.org', 'topsecret.server.com']
可选参数 source 指定一个所传入字符串的上下文专属名称。 如果未给出,则会使用 '<string>'。 这通常应为一个文件系统路径或 URL。
- 方法4:从字典对象中读取配置
read_dict(dictionary, source='<dict>')
In [18]: config_dict = {
...: "DEFAULT": {
...: "ServerAliveInterval": 45,
...: "Compression": "yes",
...: "CompressionLevel": 9,
...: "ForwardX11": "yes"
...: },
...: "bitbucket.org": {
...: "User": "hg"
...: },
...: "topsecret.server.com": {
...: "Port": 50022,
...: "ForwardX11": "no"
...: }
...: }
In [19]: config_dict
Out[19]:
{'DEFAULT': {'ServerAliveInterval': 45,
'Compression': 'yes',
'CompressionLevel': 9,
'ForwardX11': 'yes'},
'bitbucket.org': {'User': 'hg'},
'topsecret.server.com': {'Port': 50022, 'ForwardX11': 'no'}}
In [20]: config.read_dict(config_dict)
In [21]: config.sections()
Out[21]: ['bitbucket.org', 'topsecret.server.com']
以上四种方法读取到的结果相同,其中第一种方法最常用。
3. 获取sections列表
In [21]: config.sections()
Out[21]: ['bitbucket.org', 'topsecret.server.com']
4. 判断一个section是否在config中
In [23]: config.has_section("a")
Out[23]: False
In [24]: config.has_section("bitbucket.org")
Out[24]: True
# 也可以
In [22]: 'bitbucket.org' in config
Out[22]: True
5. has_option(section, option)
如果给定的 section
存在并且包含给定的 option
则返回 True
;否则返回 False
。
如果指定的 section
为 None
或空字符串
,则会使用 DEFAULT
。
In [41]: config.has_option('bitbucket.org', 'forwardx11')
Out[41]: True
6. 获取一个具体值
In [25]: config['bitbucket.org']['User']
Out[25]: 'hg'
In [26]: config['bitbucket.org'].get('User')
Out[26]: 'hg'
In [27]: config.get('bitbucket.org')['User']
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-27-32684fbb93a2> in <module>
----> 1 config.get('bitbucket.org')['User']
TypeError: get() missing 1 required positional argument: 'option'
In [28]: config.get('bitbucket.org', 'User')
Out[28]: 'hg'
In [29]: config.get('bitbucket.org')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-29-9a55d103917e> in <module>
----> 1 config.get('bitbucket.org')
TypeError: get() missing 1 required positional argument: 'option'
可以看出,get() 方法必须作用到 option
7. 默认值(DEFAULT)的作用
In [30]: config['bitbucket.org']['ForwardX11']
Out[30]: 'yes'
因为 'bitbucket.org'
中没有 'ForwardX11'
字段,所以去 'DEFAULT'
中查找 'ForwardX11'
字段,为yes
。
8. 读取特定类型的数据
配置解析器并不会猜测配置文件中值的类型,而总是将它们在内部存储为字符串。意思就是默认configparser读出来的数据全是str类型。
配置解析器提供了一系列便捷的获取方法来处理整数、浮点数和布尔值。
-
getboolean()
、getint()
和getfloat()
In [31]: config['bitbucket.org'].getboolean('ForwardX11')
Out[31]: True
In [32]: config.getboolean('bitbucket.org', 'Compression')
Out[32]: True
9. get(section, option[, fallback])
默认值会优先于回退值 (fallback
)。
例如,在我们的示例中 'CompressionLevel'
option 仅在 'DEFAULT'
session 中被指定。 如果你尝试在 'topsecret.server.com'
session 中获取它,我们将总是获取到默认值,即使我们指定了一个回退值('3'):
In [33]: config['topsecret.server.com'].get('CompressionLevel', '3')
Out[33]: '9'
返回结果:'9',即使我们指定了fallback='3'。
如果DEFAULT
中也无option,则fallback起作用:
In [34]: config['topsecret.server.com'].get('aaaaa', '3')
Out[34]: '3'
In [37]: config.get('fffff', 'aaaaa', fallback='3')
Out[37]: '3'
10. options(section)
返回指定 section 中可用选项的列表
In [40]: config.options("bitbucket.org")
Out[40]:
['user',
'serveraliveinterval',
'compression',
'compressionlevel',
'forwardx11']
注意⚠️:section 参数不能指定为 DEFAULT
网友评论