pythonstringreplacenewlineconfigparser

python ConfigParser: read configuration from string


I would like to parse a configuration string that I receive from a service and read each single paramenter. The string result is [section 1],var1 = 111,var2 = 222

My code:

#!/usr/bin/python

import ConfigParser
import io
[...]

result = decoded['result']
result = result.replace(',', '\n');
print result
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(result))
print config.get("section 1", "var2")
print config.get("section 1", "var1")

using:

res = """
[section 1]
var1 = 111
var2 = 222
"""

it works so I believe is something wrong with result.replace(',', '\n'); but if I print the result seems good. Any suggestion please?

Thank you dk


Solution

  • This should work. It was an unicode error. Next time please show the stack trace

    result = u"""
    [section 1]
    var1 = 111
    var2 = 222
    """
    print repr(result)
    config = ConfigParser.ConfigParser(allow_no_value=True)
    config.readfp(io.StringIO(result))
    print config.get("section 1", "var2")
    print config.get("section 1", "var1")
    

    output:

    u'\n[section 1]\nvar1 = 111\nvar2 = 222\n'
    222
    111