general ConfigParser question

Tim Chase python.list at tim.thechases.com
Mon Nov 25 19:29:06 EST 2013


On 2013-11-25 18:32, Rita wrote:
> I was wondering if the default ConfigParser can handle multi line
> strings (especially in the relate section)
> 
> [Relate]
> data="parent process A child process B
> Parent process B child process C

Yes, though I seem to recall that subsequent lines have to be
indented:

>>> from ConfigParser import ConfigParser as cp
>>> from StringIO import StringIO
>>> sio = StringIO("""[global]
... one ="first
...     second
...     third"
... """)
>>> c = cp()
>>> c.readfp(sio)
>>> c.get("global", "one")  # Note2: quotes
'"first\nsecond\nthird"'
>>> sio = StringIO("""[global]
... one =first
...     second
...     third
...""")
>>> c = cp()
>>> c.readfp(sio)
>>> c.get("global", "one")  # Note2: no quotes
'first\nsecond\nthird'

Note1: this also strips off leading whitespace on the subsequent
lines.

Note2: if you quote the values, they appear in the resulting value.

So based on this, I occasionally do like CherryPy does and require
quotes, then wrap my cp.get(section, name) results in a
ast.literal_eval() call to get the corresponding Python result.
Alternatively, you can use the cp.getint(), cp.getbool() and
cp.getfloat() calls.

-tkc






More information about the Python-list mailing list