简体   繁体   中英

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

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

There is a method for this called read_string on the ConfigParser object.

config = ConfigParser.RawConfigParser(allow_no_value=True)
config.read_string(result)

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