首页 > 代码库 > python标准库configparser配置解析器

python标准库configparser配置解析器

 1 >>> from configparser import ConfigParser, ExtendedInterpolation
 2 >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
 3 >>> # the default BasicInterpolation could be used as well
 4 >>> parser.read_string("""
 5 ... [DEFAULT]
 6 ... hash = #
 7 ...
 8 ... [hashes]
 9 ... shebang =
10 ...   ${hash}!/usr/bin/env python   #用ExtendedInterpolation()方法把#插入到多行values的开头,就可以把#保存下来,而不是被注释掉。
11 ...   ${hash} -*- coding: utf-8 -*-
12 ...
13 ... extensions =
14 ...   enabled_extension
15 ...   another_extension
16 ...   #disabled_by_comment
17 ...   yet_another_extension
18 ...
19 ... interpolation not necessary = if # is not at line start
20 ... even in multiline values = line #1
21 ...   line #2
22 ...   line #3
23 ... """)
24 >>> print(parser[hashes][shebang])
25 
26 #!/usr/bin/env python
27 # -*- coding: utf-8 -*-
28 >>> print(parser[hashes][extensions])
29 
30 enabled_extension
31 another_extension
32 yet_another_extension
33 >>> print(parser[hashes][interpolation not necessary])
34 if # is not at line start
35 >>> print(parser[hashes][even in multiline values])
36 line #1
37 line #2
38 line #3