简体   繁体   中英

ConfigParser.get returning a string need to convert it to section

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?

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'

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.

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