Python 允许ConfigParser将$解析为字符串,如果在插值过程中未后跟{
我想使用Python 允许ConfigParser将$解析为字符串,如果在插值过程中未后跟{,python,configparser,Python,Configparser,我想使用ConfigParser在python中的.ini文件中插入变量,并将$符号(不紧跟{符号)解析为字符串,同时仍然插入遵循${…}语法的变量 下面是一个test.ini文件示例: [variables] ; test.ini example1 = interpolate example2 = please_${example1}_me example3 = $please_leave_me_alone example4 = $foo-${example2}-$bar 使用以下代码进行分
ConfigParser
在python
中的.ini
文件中插入变量,并将$
符号(不紧跟{
符号)解析为字符串,同时仍然插入遵循${…}
语法的变量
下面是一个test.ini
文件示例:
[variables]
; test.ini
example1 = interpolate
example2 = please_${example1}_me
example3 = $please_leave_me_alone
example4 = $foo-${example2}-$bar
使用以下代码进行分析:
# python 2.7
from backports.configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser(interpolation=ExtendedInterpolation())
parser.read('test.ini')
for section in parser.sections():
for key in parser[section]:
print parser[section][key]
example2
会正确地插入到请插入我
,但是example3
和example4
都会产生一个InterpolationSyntaxError
来包含$
而不是紧接着{/code>
作为一个补丁,我可以使用带有try/except
开关的两个解析器来传递异常:
# python 2.7
from backports.configparser import ConfigParser, ExtendedInterpolation
parser1 = ConfigParser(interpolation=ExtendedInterpolation())
parser2 = ConfigParser() # to handle exceptions
parser1.read('test.ini')
parser2.read('test.ini')
for section in parser1.sections():
for key in parser1[section]:
try:
print parser1[section][key] # interpolated
except:
print parser2[section][key] # leave as is
但这并不理想,因为它不会将示例4
插入到$foo-please\u interpolate\u me-$bar
问题
ConfigParser是否可以配置为将$
符号后面不紧跟{
符号作为字符串进行解析,并且仍然插入紧跟${…}符号后面的变量
语法?我如何才能让示例4
解析为$foo-please\u interpolate\u me-$bar
?最干净的可能是将其中唯一的“$”
子类化和特殊情况。也就是说,如果值是“$”
,不要调用\u interpolate\u some(…)
,只返回值
注意:您必须这样做
(免责声明:未测试。)