0

I want to use the return value of RawConfigParser.get ('somesection', 'someoption') as the section for another RawConfigParser.get, but in practice the result is a doubly encased string.

section = RawConfigParser.get ('somesection', 'someoption')
subsection = RawConfigParser.get (section, 'someotheroption') # INCORRECT RawConfigParser.get ('"somesection"', 'someotheroption')

How do I avoid this?

user2994682
  • 503
  • 1
  • 8
  • 19
  • What does the ini file look like? It seems like the option is written as `someoption = "somesection"`. But quotes aren't generally needed in ini files and it could reasonably be considered an invalid option value that shouldn't work. – tdelaney Aug 20 '14 at 00:26

2 Answers2

2

You have a couple options, one of which is to use the ast library

>>> quoted_string = '"this is a quote"'
>>> quoted_string
'"this is a quote"'
>>> import ast
>>> unquoted_string = ast.literal_eval(quoted_string)
>>> unquoted_string
'this is a quote'
C.B.
  • 8,096
  • 5
  • 20
  • 34
  • 1
    The assumption here is that option values must be quoted. `option = "this is a quote"` would be legal but `option = this is a quote` would raise an exception. This is backwards from how config files are usually written. Given a choice, I'd prefer the quoted version fail. – tdelaney Aug 20 '14 at 00:40
0

You should realized a file-object and use RawConfigParser.readfp()

>>> help(ConfigParser.RawConfigParser.readfp)

Help on method readfp in module ConfigParser:

readfp(self, fp, filename=None) unbound ConfigParser.RawConfigParser method
    Like read() but the argument must be a file-like object.

    The `fp' argument must have a `readline' method.  Optional
    second argument is the `filename', which if not given, is
    taken from fp.name.  If fp has no `name' attribute, `<???>' is
    used.
LittleQ
  • 1,860
  • 1
  • 12
  • 14