允许ConfigParser将$解析为字符串,如果插值期间不跟{之后

时间:2019-06-12 18:19:00

标签: python configparser

我想在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_meexample3都会因包含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符号作为字符串,并且仍然插值遵循$语法的变量?我怎么能将{解析为${...}

1 个答案:

答案 0 :(得分:1)

最干净的方法可能是子类configparser.ExtendedInterpolation::before_get的子类,并在其中特例单独的"$"。也就是说,如果value"$",请不要调用_interpolate_some(...)并仅返回值。

注意:您必须pass the custom interpolation as interpolation constructor argument

(免责声明:未测试。)