ConfigParser: use newline in INI file
Peter Otten
__peter__ at web.de
Sun Oct 2 08:19:39 EDT 2016
Thorsten Kampe wrote:
> * Ned Batchelder (Sat, 1 Oct 2016 17:41:28 -0700 (PDT))
>> If you want to have \n mean a newline in your config file, you can
>> do the conversion after you read the value:
>>
>> >>> "a\\nb".decode("string-escape")
>> 'a\nb'
>
> Interesting approach (although it does not work with Python 3: decode
> is only for byte-strings and the string-escape encoding is not
> defined).
The equivalent for Python 3 is
>>> import codecs
>>> codecs.decode("a\\nb", "unicode-escape")
'a\nb'
You can teach ConfigParser to do this automatically with a custom
Interpolation:
$ cat cpdemo.py
#!/usr/bin/env python3
import configparser as cp
import codecs
class MyInterpolation(cp.BasicInterpolation):
def before_get(self, parser, section, option, value, defaults):
return super().before_get(
parser, section, option,
codecs.decode(value, "unicode-escape"),
defaults)
p = cp.ConfigParser(interpolation=MyInterpolation())
p.read_string("""\
[foo]
bar=ham\\nspam
""")
print(p["foo"]["bar"])
$ ./cpdemo.py
ham
spam
More information about the Python-list
mailing list