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

4
  • 1
    Can you write the output of print repr(result) Commented Jan 2, 2015 at 15:08
  • Dear Xavier, here the result u'[section 1]\nvar1 = 111\nvar2 = 222' Commented Jan 2, 2015 at 15:12
  • fixed it with result = result.encode('ascii','ignore') Commented Jan 2, 2015 at 15:23
  • It is not the good way to fix it, please see my answer Commented Jan 2, 2015 at 15:25

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

1 Comment

the above code throwing the below error. globals.CF_currFile=config.read_string('CustomFile','LastCustomFileAccessed') AttributeError: RawConfigParser instance has no attribute 'read_string'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.