我想在ConfigParser
的{{1}}文件中使用interpolate
到.ini
变量,并解析python
符号,不要紧跟着$
符号作为字符串,同时仍插值遵循{
语法的变量。
这是一个${...}
文件示例:
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
,但是please_interpolate_me
和example3
都会因包含example4
而引起InterpolationSyntaxError
,而不会紧跟{ {1}}。
作为补丁,我可以使用两个带有$
开关的解析器来传递异常:
{
但这并不理想,因为它无法将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
问题
是否可以将ConfigParser配置为解析example4
符号而不是紧跟其后的$foo-please_interpolate_me-$bar
符号作为字符串,并且仍然插值遵循$
语法的变量?我怎么能将{
解析为${...}
?
答案 0 :(得分:1)
最干净的方法可能是子类configparser.ExtendedInterpolation::before_get
的子类,并在其中特例单独的"$"
。也就是说,如果value
是"$"
,请不要调用_interpolate_some(...)
并仅返回值。
注意:您必须pass the custom interpolation as interpolation
constructor argument。
(免责声明:未测试。)