2

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

d82k
  • 379
  • 7
  • 17

2 Answers2

4

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
Xavier Combelle
  • 10,968
  • 5
  • 28
  • 52
2

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

config = ConfigParser.RawConfigParser(allow_no_value=True)
config.read_string(result)
monokrome
  • 1,377
  • 14
  • 21
  • the above code throwing the below error. globals.CF_currFile=config.read_string('CustomFile','LastCustomFileAccessed') **AttributeError: RawConfigParser instance has no attribute 'read_string'** – Anjali Nov 02 '18 at 11:49