python标准库configparser配置解析器

本文详细介绍了如何利用ExtendedInterpolation方法在配置文件中保留注释信息,并正确处理多行值。通过实例演示了如何读取包含特殊注释符号的配置字符串,以及如何打印解析后的键值对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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

 

转载于:https://www.cnblogs.com/cnbubble/p/3762307.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值