简体   繁体   中英

Allow ConfigParser to parse $ as a string if not followed by { during interpolation

I want to use ConfigParser to interpolate variables in a .ini file in python and parse $ symbols not immediately followed by { symbol as strings while still interpolate variables that follow the ${...} syntax.

Here's a test.ini file example:

[variables]
; test.ini
example1 = interpolate
example2 = please_${example1}_me
example3 = $please_leave_me_alone
example4 = $foo-${example2}-$bar

Parsed with this code:

# 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 would properly interpolate to please_interpolate_me but example3 and example4 would both raise an InterpolationSyntaxError for containing $ not immediately followed by { .

As a patch I could use two parsers with a try/except switch to get passed the exception:

# 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

But this is not ideal as it would not interpolate example4 to $foo-please_interpolate_me-$bar

QUESTION

Can ConfigParser be configured to parse $ symbols not immediately followed by { symbols as strings and still interpolate variables that follow the ${...} syntax? How could I get example4 to parse as $foo-please_interpolate_me-$bar ?

The cleanest would likely be to subclass configparser.ExtendedInterpolation::before_get and special-case the lone "$" in it. That is, if value is "$" , do not call _interpolate_some(...) and just return the value.

Note: you will have to pass the custom interpolation as interpolation constructor argument .

(Disclaimer: did not test.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM